0

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.

LHH
  • 3,233
  • 1
  • 20
  • 27
user984621
  • 46,344
  • 73
  • 224
  • 412

2 Answers2

1

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.

Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20
1

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.

Ziv Galili
  • 1,405
  • 16
  • 20