我有两个型号
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中执行此操作?
答案 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)
您需要将name
和belongs_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'