我有User
模型和Message
模型。我的message
表包含created_for
列和created_by
列,这些列都是User
表的外键。
我目前收到此错误消息:
对于#` , undefined method
created_for_id'
如何在不将列更改为created_for_id
和created_by_id
的情况下将其生效?
class User < ActiveRecord::Base
has_one :message
end
class Message < ActiveRecord::Base
#belongs_to :user
belongs_to :created_by, :class_name => "User" # Basically tell rails that created_by is a FK to the users table
belongs_to :created_for, :class_name => "User" # Basically tell rails that created_for is a FK to the users table
attr_accessible :created_by, :created_for, :message
end
答案 0 :(得分:2)
您可以通过以下方式指定belongs_to的外键:
belongs_to :created_for, class_name: 'User', foreign_key: :created_for
我怀疑您将遇到一个问题,即关系名称和外键属性共享一个名称。这是belongs_to文档,向下滚动到“选项”