一個更好的辦法是使用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 here
:http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
你可以在視圖中有兩種形式並相互獨立地提交它們,但我不知道如何在同一時間提交它們。 – rubish
那麼這是不可能的? – Immo
我的意思是,如果你使用ajax進行獨立提交比沒有問題,你可以等待表單提交的響應。儘管如此,我仍然懷疑有關問題和答案。通過http提交,我無法一次性提交兩個請求。可能是第一個請求將被客戶端忽略。可能是客戶會迴應任何迴應先來。但是,不管發生什麼,那裏都有很多難聞的氣味。 – rubish