記事を投稿したする際に子モデルのカテゴリーにも同時にレコード追加したいのですが、うまくいきません。
記事を投稿するページにアクセス(newアクション)すると、以下のエラーになってしまいます。
unknown attribute 'postit_id' for Postitcategory. @postit.postitcategories.build
子モデルとの関連付け方が良くないのだと思うのですが、どのようにすればよいでしょうか?
ご回答いただけると助かります。
#コントローラ
postits_controller
ruby
1def new 2 @postit = Postit.new 3 @postit.postitcategories.build 4end
モデル
モデルの関係は Postit 1対多 Postitcategory
です。
Postit
id | title | postitcategory_id | name | content |
---|---|---|---|---|
1 | テスト | 1 | 太郎 | 内容 |
2 | Railsについて | 2 | 太郎 | 内容 |
ruby
1class Postit < ApplicationRecord 2 has_many :postitcategories 3 4 accepts_nested_attributes_for :postitcategories 5end 6
Postitcategory
id | category |
---|---|
1 | 日常 |
2 | 開発 |
ruby
1class Postitcategory < ApplicationRecord 2 belongs_to :postit, optional: true 3end
View
ruby
1<%= form_with(model: postit, local: true) do |form| %> 2 <div class="field"> 3 <%= form.label :title %> 4 <%= form.text_field :title %> 5 </div> 6 7 <div class="field"> 8 <%= fields_for(:postitcategories) do |c| %> 9 <%= c.label :category %> 10 <%= c.text_field :category %> 11 <% end %> 12 </div> 13 14 <div class="field"> 15 <%= form.label :name %> 16 <%= form.text_field :name %> 17 </div> 18 19 <div class="field"> 20 <%= form.label :content %> 21 <%= form.text_field :content %> 22 </div> 23 24 <div class="actions"> 25 <%= form.submit %> 26 </div> 27<% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/25 16:17
2018/07/26 10:30
2018/07/27 01:25