前提・実現したいこと
form_withでネストしたモデルにデータを送って保存したい。
発生している問題・エラーメッセージ
Showing /vagrant/canatap/app/views/place_talks/index.html.erb where line #150 raised: undefined method `contents' for nil:NilClass
該当のソースコード
rails5
1 2[view]place_talks/index.html.erb 3 4<%= form_with model: Location.new, url: place_talks_path,method: :post,class:"submit" do |f| %> 5 <h6>Comment</h6> 6 <%= f.text_field :comment,class: "location_comment"%> 7 8 <h6>作品名</h6> 9 <%= f.fields_for :contents, @location.contents.build do |ff| %> 10 <%= ff.text_field :name, class: "location_contents"%> 11 <% end %> 12 </span></p> 13 <%= f.submit "作成"%> 14 <% end %> 15 16[controller] 17 18 def create 19 @location = Location.new(location_params) 20 @location.contents.build 21(中略) 22 private 23 def location_params 24 params.require(:location).permit(:comment, contents_attributes:[:id,:name]) 25 end 26 27[model]location:rb 28 29 has_many :contents 30 accepts_nested_attributes_for :contents 31 32[model]content:rb 33 34 belongs_to :location
試したこと
https://qiita.com/onigirimantarou/items/1281093334b38a9cd67c
こちらを参考に試しましたがどうしてもうまくいきません・・・。
[view]の「@location.contents.build」の部分を
[controller]のcreateアクションにうつして試しましたがこちらは
エラーは出ないものの、
<%= f.fields_for :contents, @location.contents.build do |ff| %>
部分のフォームのみ表示されなくなります。
補足情報(FW/ツールのバージョンなど)
index.html.erbからform_withでcreateアクションに飛ばしていて、newは使用していません。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。