使用外键选择关联的模型

时间:2013-11-21 19:08:36

标签: ruby-on-rails ruby ruby-on-rails-4 associations

我有两个型号

class Endorsement < ActiveRecord::Base
  belongs_to :user, foreign_key: "endorser_id"
  belongs_to :user, foreign_key: "endorsee_id"
end

class User < ActiveRecord::Base
  # Contains a name attribute

  has_many :endorsements, foreign_key: "endorser_id"
  has_many :endorsements, foreign_key: "endorsee_id"
end

我想得到代言人的名字。当我endorsement.user.name时,当我真正想要endorsee_id的名字时,我会收到endorser_id的名字。我如何在Rails中执行此操作?

3 个答案:

答案 0 :(得分:2)

class Endorsement < ActiveRecord::Base
  belongs_to :endorser, class_name: "User", foreign_key: "endorser_id"
  belongs_to :endorsee, class_name: "User", foreign_key: "endorsee_id"
end

class User < ActiveRecord::Base
  # Contains a name attribute
  has_many :endorsements, foreign_key: "endorser_id"
  has_many :endorsements, foreign_key: "endorsee_id"
end

endorsement.endorser.name

答案 1 :(得分:2)

您需要将namebelongs_to的{​​{1}}部分重命名为唯一,然后将has_many附加到该关系,以便Rails知道要查看哪个模型at:

class_name:

这将允许您执行以下所有操作:

class Endorsement < ActiveRecord::Base
  belongs_to :endorser, foreign_key: "endorser_id", class_name: "User"
  belongs_to :endorsee, foreign_key: "endorsee_id", class_name: "User"
end

class User < ActiveRecord::Base
  # Contains a name attribute

  has_many :has_endorsed, foreign_key: "endorser_id", class_name: "Endorsement"
  has_many :endorsements, foreign_key: "endorsee_id", class_name: "Endorsement"
end

答案 2 :(得分:0)

这是因为你要覆盖这段关系。您需要使用class_name参数。这样的事情。

belongs_to :endorser, class_name: 'User', foreign_key: 'endorser_id'
belongs_to :endorsee, class_name: 'User', foreign_key: 'endorsee_id'

用户模型也是如此。

has_many :endorsers, class_name: 'Endorsement', foreign_key: 'endorser_id'
has_many :endorsees, class_name: 'Endorsement', foreign_key: 'endorsee_id'