Rails - one model with two associations

一曲冷凌霜 提交于 2019-12-08 07:57:06

问题


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)

回答1:


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}


来源:https://stackoverflow.com/questions/9934308/rails-one-model-with-two-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!