关于ruby on rails:ActiveModel :: UnknownAttributeError:事件的未知属性’creator_id’

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

当我尝试与创建者创建事件时,它说ActiveModel::UnknownAttributeError: unknown attribute 'creator_id' for Event.
我运行rails db:migrate,但仍然不会创建外键并添加到事件表中。我究竟做错了什么?我到处都看着。

$ 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

foreign_key始终存在于子表中。尝试如下创建事件。

正在考虑用户已经登录。

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