显式指定Rails模型外键时不工作



我有一个User模型和一个Message模型。我的message表有created_forcreated_by列,它们都是User表的外键。

我现在得到这个错误信息:

undefined method created_for_id' for # '

我怎么能得到这个工作,而不必改变我的列created_for_idcreated_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"

相关内容

  • 没有找到相关文章

最新更新