Multiple has_many: through

In the object model, I have

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

How do I get a list of users for like? For instance. object.users <--- but how can I indicate through sympathy or hatred?

+6
source share
3 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 
+6
source

It seems I need to add a source too. If not Rails will look 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' 
+1
source

You can do it like:

 has_many :user_likes, :through => :likes, :class_name => 'User' 
0
source

Source: https://habr.com/ru/post/909799/


All Articles