Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple has_many :through

In object model, I have

has_many :likes
has_many :hates
has_many :users, :through => :likes
has_many :users, :through => :hates

How do I get the list of users for likes? E.g. object.users <--- but how do I specify through likes or hates?

like image 809
Min Ming Lo Avatar asked Mar 02 '12 05:03

Min Ming Lo


2 Answers

You need to give these two different associations different names. What about

has_many :likes
has_many :hates
has_many :likers, :through => :likes, :source => :user
has_many :haters, :through => :hates, :source => :user
like image 154
Ben Taitelbaum Avatar answered Nov 20 '22 16:11

Ben Taitelbaum


It seems that I need to add source too. If not Rails will be looking for likers/liker in likes.

has_many :likes
has_many :hates
has_many :likers, :through => :likes, :class_name => 'User', :source => 'user'
has_many :haters, :through => :hates, :class_name => 'User', :source => 'user'
like image 26
Min Ming Lo Avatar answered Nov 20 '22 16:11

Min Ming Lo