このサイトを参考に1つのform_forで複数モデルへデータ登録をする方法を試していたのですが
error
1ActiveModel::UnknownAttributeError (unknown attribute 'answer_id' for Notification.):
というエラーが出てしまいます。answerモデルとnotificationsモデルの関係がうまく行っていないのかなと思いforeign_keyを指定してみたりしたのですがうまくいきません。なにかわかる方はコメント回答お願いします。
answerrb
1class Answer < ApplicationRecord 2 has_many :notifications 3 accepts_nested_attributes_for :notifications 4end
Notificationrb
1class Notification < ApplicationRecord 2 belongs_to :answer, optional: true 3 belongs_to :comment, optional: true 4 belongs_to :man, foreign_key: :visiter_id 5end
answercontroller
1class AnswersController < ApplicationController 2 3(省略) 4 5 private 6 7 def answer_params 8 params.require(:answer).permit(:question_id, :content, :answer_id, notifications_attributes:[:visiter_id, :visited_id, :post_id, :action]) 9 end 10end
form.html.erb
1<%= form_with model: @answer do |f| %> 2 3 <%= f.hidden_field :question_id, {value: answer.question_id} %> 4 5 <%= f.rich_text_area :content %> 6 7 <%= f.hidden_field :answer_id, { value:current_man.id } %> 8 9 <%= f.fields_for :notifications do |i| %> 10 <%= i.hidden_field :visiter_id, { value:current_man.id } %> 11 <%= i.hidden_field :visited_id, { value:@user.id } %> 12 <%= i.hidden_field :post_id, { value:answer.question_id } %> 13 <%= i.hidden_field :action, { value:'answer' } %> 14 <% end %> 15 16 <%= f.submit '回答する' %> 17 18 19<% end %> 20
dbnotifications
1def change 2 create_table :notifications do |t| 3 t.integer :visiter_id 4 t.integer :visited_id 5 t.integer :post_id 6 t.integer :comment_id 7 t.string :action 8 t.boolean :checked, default: false, null: false 9 10 t.timestamps 11 end 12 end
dbanswers
1def change 2 create_table :answers do |t| 3 t.integer :question_id 4 t.text :content 5 t.integer :answer_id 6 7 t.timestamps 8 end 9 end
回答1件
あなたの回答
tips
プレビュー