我有3個模型接受問題和問題的嵌套屬性的項目接受嵌套屬性的答案。我試圖用相同的形式創建一個有問題和答案的項目。Deep Nested Rails 4表格
item.rb的
class Item < ActiveRecord::Base
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
question.rb
answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
end
item_controller.rb
class ItemsController < ApplicationController
def new
@item = @repository.items.new
questions = @item.questions.build
answers = questions.answers.build
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to @item, notice: '...'
else
render action: 'new'
end
end
private
def item_params
params.require(:item).permit(:id, :content, :kind, :questions_attributes => [:content, :helper_text, :kind], :answers_attributes => [:content, :correct])
end
end
_form.haml
= simple_form_for(@item) do |f|
= f.input :kind
= f.input :content
= f.simple_fields_for :questions do |q|
= q.input :content
= q.simple_fields_for :answers do |a|
= a.input :content
= f.submit
的形式被正確顯示和它正確保存的問題模型。雖然我似乎無法保存答案。
我已經看過很多在線幫助,但沒有一篇介紹Rails 4強參數。
很好的解釋+1 –
我想這將是例子類似這樣的答案,但感謝。 – etusm