6

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?

Min Ming Lo
  • 2,398
  • 2
  • 18
  • 25

3 Answers3

6

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
Ben Taitelbaum
  • 7,343
  • 3
  • 25
  • 45
  • That's what I thought, too, but the documentation of `has_many` (in ActiveRecord::Associations::ClassMethods) says: "`:through` specifies an association through which to perform the query. [...] Options for `:class_name`, `:primary_key` and `:foreign_key` **are ignored**, as the association uses the source reflection." – so, the `:class_name` won't do anything, will it? – fanaugen Jul 11 '12 at 08:47
  • You're right, I updated the example to be compliant with the documentation, where it references the source association, from which it can be inferred that it's a User object. – Ben Taitelbaum Jul 11 '12 at 09:35
  • I think the `:source => :user` should be `:source => :users`. – Hassan Akram Apr 24 '16 at 13:09
1

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'
Min Ming Lo
  • 2,398
  • 2
  • 18
  • 25
0

You can do it like :

has_many :user_likes, :through => :likes, :class_name => 'User'
Spyros
  • 46,820
  • 25
  • 86
  • 129