ActiveModel::UnknownAttributeError: unknown attribute 'creator_id' for Event
1 2 3 4 5 6 7 | class User < ApplicationRecord has_many :created_events, :foreign_key =>"creator_id", :class_name =>"Event" end class Event < ApplicationRecord belongs_to :creator, :class_name =>"User" end |
当我尝试与创建者创建事件时,它说
我运行
$ rails db:migrate:status
1 2 3 4 5 6 | Status Migration ID Migration Name -------------------------------------------------- up 20170625163737 Create users up 20170625170905 Create events up 20170625171959 Add description to event up 20170625174531 Add creator id to events |
但是,迁移文件显示未添加任何内容:
1 2 3 4 | class AddCreatorIdToEvents < ActiveRecord::Migration[5.1] def change end end |
您尚未正确定义关联。您的模型应如下所示:
1 2 3 4 5 6 7 | class User < ApplicationRecord has_many :events, :foreign_key =>"creator_id", :class_name =>"Event" end class Event < ApplicationRecord belongs_to :creator, :foreign_key =>"creator_id", :class_name =>"User" end |
也
正在考虑用户已经登录。
1 | current_user.events.create(event_params) |
请参阅此以获得与关联相关的帮助。
您的模型应如下所示:
1 2 3 4 5 6 7 | class User < ApplicationRecord has_many :created_events, :foreign_key =>"creator_id", :class_name => "Event" end class Event < ApplicationRecord belongs_to :creator, :foreign_key =>"creator_id", :class_name =>"User" end |