我有一个User
模型和一个Message
模型。我的message
表有created_for
和created_by
列,它们都是User
表的外键。
我现在得到这个错误信息:
undefined method
created_for_id' for # '
我怎么能得到这个工作,而不必改变我的列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
可以通过以下方式指定belongs_to的外键:
belongs_to :created_for, class_name: 'User', foreign_key: :created_for
我怀疑您将遇到关系名称和外键属性共享名称的问题。下面是belongs_to文档,向下滚动到"Options"