Rails 3ネストされたモデルフォーム、comppods_nested_attributes_forを使用して2レベルの深さ
-
30-10-2019 - |
質問
私のネストされたモデルフォームは、最初のレベルの深さでうまく機能しています。しかし、私はあなたがAccepts_nested_attributes_forを使用して多くのレベルを深くすることができるという印象を受けていました。ただし、以下のコードを試すと、「画像」属性が上位レベルの「質問」モデルに添付され、「画像」エラーが不明な属性でフォームの送信時に折れます。
フォームデータを使用してすべてのインサートを手作業で実行できますが、Railsが自動的に処理できる場合は、明らかな理由で優れています。
私は何が間違っているのですか?変更を試みました| af | 「フィールドの:Image Do」では、独自のユニークな名前になりましたが、効果はありませんでした。
モデル:
class Question < ActiveRecord::Base
has_one :answer
accepts_nested_attributes_for :answer
end
class Answer < ActiveRecord::Base
belongs_to :question
has_one :image
accepts_nested_attributes_for :image
end
class Image < ActiveRecord::Base
belongs_to :answer
end
コントローラ:
def new
@question = Question.new
answer = @question.build_answer
image = answer.build_image
@case_id = params[:id]
render :layout => 'application', :template => '/questions/form'
end
def create
question_data = params[:question]
@question = Question.new(question_data)
if @question.save
...
end
意見:
= form_for @question, :html => {:multipart => true} do |f|
= f.label :text, "Question Text:"
= f.text_area :text, :rows => 7
%br
%br
=f.fields_for :answer, do |af|
= af.label :body, "Answer Text:"
= af.text_area :body, :rows => 7
%br
%br
= f.fields_for :image do |af|
= af.label :title, "Image Title:"
= af.text_field :title
%br
= af.label :file, "Image File:"
= af.file_field :file
%br
= af.label :caption, "Image Caption:"
= af.text_area :caption, :rows => 7
= hidden_field_tag("case_id", value = @case_id)
= f.submit
正しい解決策はありません
所属していません StackOverflow