当显式指定时,Rails模型外键不起作用

时间:2014-03-21 01:04:50

标签: ruby-on-rails ruby ruby-on-rails-3

我有User模型和Message模型。我的message表包含created_for列和created_by列,这些列都是User表的外键。

我目前收到此错误消息:

对于#`

undefined method created_for_id'

如何在不将列更改为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

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式指定belongs_to的外键:

belongs_to :created_for, class_name: 'User', foreign_key: :created_for

我怀疑您将遇到一个问题,即关系名称和外键属性共享一个名称。这是belongs_to文档,向下滚动到“选项”