2

I have 2 models: User and PrivateMessage which must be associated (as user has many private messages as reciever and sender, private messages belongs to user)

It's my private_messages table structure:

private_messages:
  sender_id:integer
  reciever_id:integer
  title:string
  message:text

It's hard for me to understand how can I connect same message for both sender user and reciever user, now my models code looks like:

class User < ActiveRecord:Base
  has_many :private_messages
end

and

class PrivateMessage < ActiveRecord::Base
  belongs_to :user, :through => :sender_id
  belongs_to :user, :through => :reciever_id
end

Is that correct?

1 Answer 1

5

You have to rename your associations to tell them apart:

class PrivateMessage < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
  belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id'
end

class User < ActiveRecord::Base
  has_many :sent_messages, :class_name => 'PrivateMessage', :foreign_key => 'sender_id', :dependent => :destroy
  has_many :received_messages, :class_name => 'PrivateMessage', :foreign_key => 'receiver_id', :dependent => :destroy
end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.