views:

24

answers:

1

I have two classes Message and User. Message has sender_id and recipient_id both foreign keys for User. How to build relationship where I'll be able to get user for both sender and recipient, like @message.sender.name and @message.recipient.name

I tried to do it by this way:

class Message < ActiveRecord::Base  

  belongs_to :sender, :class_name => 'User', :foreign_key => 'sender'
  belongs_to :recipient, :class_name => 'User', :foreign_key => 'recipient'

end   

class User < ActiveRecord::Base

  has_many :recivied_messages, :class_name => 'Message', :foreign_key => 'recipient'
  has_many :send_messages, :class_name => 'Message', :foreign_key => 'sender'
end

But it didn't help, when I'm trying to access to, for instance, @message.recipient.name it says that "undefined method `name'"

A: 

You can use the :class_name property to set which class gets used for a foreign key:

class Message < ActiveRecord::Base
  has_one :sender, :class_name => User
  has_one :recipient, :class_name => User
end

class User < ActiveRecord::Base
  belongs_to :sent_messages, :class_name => Message
  belongs_to :received_messages, :class_name => Message
end

Also, you say you are using sender_id and recipient_id for the foreign keys, but in your code you have :foreign_key => 'sender' and :foreign_key => 'recipient'. Have you tried changing them to :foreign_key => 'sender_id' and :foreign_key => 'recipient_id'? So:

class Message < ActiveRecord::Base
  has_one :sender, :class_name => User, :foreign_key => 'sender_id'
  has_one :recipient, :class_name => User, :foreign_key => 'recipient_id'
end

class User < ActiveRecord::Base
  belongs_to :sent_messages, :class_name => Message, # ...etc
  belongs_to :received_messages, :class_name => Message, # ...etc
end
W_P
Tried this way but didn't work
Arty
what do you mean by didn't work? did you get an error message? wrong data? this is a two-way street :p
W_P
I updated topic with the example of code, because it's no possible to post it in comment :)
Arty
Edited answer...
W_P
yeah, I've noticed this mistake also and fixed it, but didn't help either :(
Arty
it would help if you could find out more about what you are getting...do you know how to use `irb` with rails models? http://guides.rubyonrails.org/command_line.html#console
W_P
Ha, that helped, thank you. It was stupid mistake, just used the wrong class. Your method works
Arty