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
当我尝试使用创建者创建活动时,会显示ActiveModel::UnknownAttributeError: unknown attribute 'creator_id' for Event.
我运行rails db:migrate
但仍然没有创建外键并添加到事件表。我究竟做错了什么?我到处看着。
$ rails db:migrate:status
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
但是,迁移文件显示没有添加:
class AddCreatorIdToEvents < ActiveRecord::Migration[5.1]
def change
end
end
答案 0 :(得分:1)
您尚未正确定义关联。您的模型应如下所示:
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
同样foreign_key
始终存在于子表中。尝试创建如下的事件。
考虑用户已登录。
current_user.events.create(event_params)
请参阅this以获取与协会相关的帮助。
答案 1 :(得分:0)
您的模型应如下所示:
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