简体   繁体   中英

Rails 4 - how to use “belongs_to” on the same model twice (once with using “foreign_key”)?

I have a model 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

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM