Search code examples
ruby-on-railsrubymodelforeign-keysbelongs-to

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.


Solution

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