実装したいことと現状の問題点
Rails5で親子孫のアソシエーションの作り、一つの投稿フォームから投稿できるようにしたいのですが、親子までの部分であれば、投稿はできるようになったのですが、そこに孫テーブルにも同じフォームから投稿してデータを入れたいのですが、エラーが出てしまっています。
関連コード
Model
1class Parent < ApplicationRecord 2 #Childrenとのアソシエーション(1:多) 3 has_many :children 4 accepts_nested_attributes_for :children 5end 6 7class Child < ApplicationRecord 8 #parentsとのアソシエーション(1:多) 9 belongs_to :parent, optional: true 10 11 #Grandchildとのアソシエーション(1:1) 12 has_one :grandchild 13 accepts_nested_attributes_for :grandchild 14end 15 16class Grandchild < ApplicationRecord 17 #childとのアソシエーション(1:1) 18 belongs_to :child 19end
view
1<%= form_for(@parents, url:{controller:'parents', action:'create'})do |f| %> 2... 3 <%= f.fields_for :children do |i| %> 4 ... 5 <%= i.fields_for :grandchild do |ii| %> 6 ... 7 <% end %> 8 <% end %> 9<% end %>
controller
1class ParentsController < ApplicationController 2 def new 3 @parents = Parent.new 4 @parents.children.build 5 @parents.children.grandchild.build 6 end 7 8 private 9 def submit_params 10 params.require(:parent).permit(:name, :old, children_attributes: [:name,:old, grandchild_attributes: %(name)]) 11 end 12end
発生しているエラー
コントローラーの「@parents.children.grandchild.build」でNoMethodErrorが出てしまっています。
試したこと
エラーが出ている部分の書き方を様々なサイトを参考に少し変えたり、(ex.)しましたが、直らず。
「@parents.children.grandchild.build」を消すと、Viewでエラーが出たりしていました。
その他
プログラミング歴が浅く、言葉など伝わりづらい部分があるかと思いますが、何卒よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー