我有两个模型,User和Event。每个活动都有一个唯一的管理员,他是一个用户角色。
当我m trying to access @event.admin i get my admin user but if I
尝试访问@ user.administered_events以获取事件时,会显示此消息。
ActiveRecord :: StatementInvalid:Mysql :: Error:'where子句'中的未知列'events.user_id':SELECT events
。* FROM events
WHERE(events
。user_id = 5)
Rails尝试从Event而不是admin_id访问user_id。我做错了什么?
class User < ActiveRecord::Base
has_many :administered_events, :class_name => "Event"
end
class Event < ActiveRecord::Base
belongs_to :admin, :class_name => "User"
end
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.string :title
t.date :date
t.string :status
t.integer :admin_id
t.timestamps
end
end
def self.down
drop_table :events
end
end
答案 0 :(得分:1)
在声明关联时尝试使用:foreign_key选项:
class User < ActiveRecord::Base
has_many :administered_events, :class_name => "Event", :foreign_key => "admin_id"
end
class Event < ActiveRecord::Base
belongs_to :admin, :class_name => "User"
end
来自Rails文档:
按照惯例,Rails猜测了 用于保存外键的列 另一个模型就是这个名字 添加了后缀_id的模型。该 :foreign_key选项允许您设置 直接输入外键的名称。
答案 1 :(得分:0)
尝试:
class User < ActiveRecord::Base
has_many :administered_events, :class_name => "Event" , foreign_key => "admin_id"
end