2011-07-25 93 views
3

是否可以在一個視圖中有兩個表單並同時提交兩個表單?從1a頁面提交兩個表格

我不想使用嵌套窗體。

例如:

我:

Model Survey 
|_question_id 
|_answers_id 

Model Question: 
|_text 

Model Answer 
|_text 

是否有可能做,沒有嵌套形式?例如,我想創建一個新問題(表單1)和一個新答案(表單2),並在控制器的創建方法中,我將創建一個新的調查問卷,並將question_id和answers_id分配給新創建的問題,相應地回答!

感謝

+0

你可以在視圖中有兩種形式並相互獨立地提交它們,但我不知道如何在同一時間提交它們。 – rubish

+0

那麼這是不可能的? – Immo

+1

我的意思是,如果你使用ajax進行獨立提交比沒有問題,你可以等待表單提交的響應。儘管如此,我仍然懷疑有關問題和答案。通過http提交,我無法一次性提交兩個請求。可能是第一個請求將被客戶端忽略。可能是客戶會迴應任何迴應先來。但是,不管發生什麼,那裏都有很多難聞的氣味。 – rubish

回答

7

一個更好的辦法是使用accepts_nested_attributes_for通過一個表單提交構建所有三種型號。

設置你的模型像這樣:

class Survey < ActiveRecord::Base 
    has_one :question 
    has_many :answers 

    accepts_nested_attributes_for :question, :answers 
end 

class Question < ActiveRecord::Base 
    belongs_to :survey 
end 

class Answer < ActiveRecord::Base 
    belongs_to :survey 
end 

然後你就可以使用Rails助手這樣寫你的表格:

<%= form_for @survey do |form| %> 
    <%= form.fields_for :question do |question_form| %> 
    <%= question_form.text_field :question 
    <% end %> 
    <%= form.fields_for :answers do |answer_form| %> 
    <%= question_form.text_field :answer 
    <% end %> 
    <%= form.submit %> 
<% end %> 

在控制器的行動,將使你需要建立形式內存中的新記錄如下:

class SurveyController < ApplicationController 
    def new 
    @survey = Survey.new 
    @survey.build_question 
    @survey.answers.build 
    end 
end 

您可以閱讀更多關於accepts_nested_attributes_for herehttp://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

+0

非常感謝:) – Immo

+0

如果其中一個模型has_many而不是has_one。這是否需要更改? – Immo

+0

我已將示例更改爲has_many答案 –