user984621
user984621

Reputation: 48443

Rails - one model with two associations

I have the model Member that contains all informations about the registered member on my site. Then I have the model Message which contains 2 columns (actually 3 with id):

- member_id
- message_from

In the table Messages are stored IDs of user, how chatting together - when the member A send message to member B, so in the column member_id is saved ID of person A and into the column message_from ID of the person B.

My current associations looks like:

class Member < ActiveRecord::Base
  has_many :messages_from
end

class Message < ActiveRecord::Base
  belongs_to :member
end

I don't know, how could I get the name of the person stored in the column message_from - when I try

- @member.messages_from.each do |mess_from|
    ={mess_from.name}

so I get the error undefined method "name" for... How could I get the name of the user through ID that is stored in the column message_from?

EDIT - update relations:

class Member < ActiveRecord::Base
  has_many :messages
end

class Message < ActiveRecord::Base
  belongs_to :member, :foreign_key => 'user_id', :class_name => 'Member'
  has_one :member, :foreign_key => 'message_from', :class_name => 'Member'
end

gives me:

- @member.messages.each do |message|
    = message.message_from.inspect # => "110"
    = message.message_from.inspect # => undefined method `name' for "110":String (I wanna get the name of person with ID 110)

Upvotes: 1

Views: 809

Answers (1)

Deradon
Deradon

Reputation: 1787

I'd do something like this:

# Untested code, please check yourself!
class Member < ActiveRecord::Base
  has_many :outgoing_messages, :class_name  => "Message", 
                               :foreign_key => :message_from_id
  has_many :incoming_messages, :class_name  => "Message",
                               :foreign_key => :message_to_id
end


class Message < ActiveRecord::Base
  belongs_to :sender, :class_name  => "Member", 
                      :foreign_key => :message_from_id
  belongs_to :receiver, :class_name  => "Member", 
                        :foreign_key => :message_to_id
end

More to read about associations here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

EDIT: In your views:

- @member.outgoing_messages.each do |message|
    ={message.receiver.name}
    ={message.sender.name}

Upvotes: 4

Related Questions