[英]Rails 4 - how to use “belongs_to” on the same model twice (once with using “foreign_key”)?
I have a model Message
: 我有一个模型
Message
:
class Message < ActiveRecord::Base
belongs_to ...
belongs_to ...
belongs_to :user
belongs_to :user, class_name: "User", foreign_key: "accepted_denied_by_user_id"
end
With this setup, if I call: 使用此设置,如果我打电话:
message.user.email
I get email of the user who accepted the message, but not who sent it. 我收到了接受邮件但未发送邮件的用户的电子邮件。
If I remove this line: 如果我删除此行:
belongs_to :user, class_name: "User", foreign_key: "accepted_denied_by_user_id"
and call: 并致电:
message.user.email message.user.email
I get the email of a user who sent out the message. 我收到发送该消息的用户的电子邮件。
How can I get the email of the sender and also the recipient? 如何获得发件人和收件人的电子邮件?
I tried 我试过了
message.accepted_denied_by_user.email
but this leads to 但这导致
undefined method `accepted_denied_by_user' for ...
Thank you. 谢谢。
It should be like this: 应该是这样的:
belongs_to :user
belongs_to :accepted_denied_by_user, class_name: "User", foreign_key: "accepted_denied_by_user_id"
Now you should be able to call both message.user.email
and message.accepted_denied_by_user.email
for specific cases. 现在,对于特定情况,您应该能够同时调用
message.user.email
和message.accepted_denied_by_user.email
。
You need to name the second association with different name: 您需要使用不同的名称来命名第二个关联:
belongs_to :denied_user, class_name: "User", foreign_key: "accepted_denied_by_user_id"
and then you will be able to get the info as: 然后您将能够获得以下信息:
message.denied_user.email
you shouldn't give two (or more) associations the same name. 您不应该给两个(或多个)关联使用相同的名称。
when you do belongs_to :user
it automatically looks for the User
model. 当您执行
belongs_to :user
它会自动查找User
模型。 but when you want to associate it again - just give it some other name, and then specify class_name: "User"
- so its still looking in the User
model, but with the foreign_key
you specified. 但是,当您要再次将其关联时-只需为其提供其他名称,然后指定
class_name: "User"
-因此其仍在User
模型中查找,但与您指定的foreign_key
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.