How to manage 3 many models in Rails

I follow the Railscast tip on creating a different relationship model many-to-many. However, I am having problems retrieving transitive relationship data.

Imagine there are 3 many-to-many models: User <-> Color <-> Shades

I made two more models:

ColorLiking (maintains User <-> Color), DiffShades (maintains Color <-> Shades)

Question Now, if everything is set up correctly ... how to find Shadeswhich belong User?

How to set up this relationship?

class User < ActiveRecord::Base
   has_many :shades, :through=>:diffShades, :source => :color
end

doesn't seem to work ...

Using SQL, the query below will work:

select * from shades 
  where id in (select shade_id from diffshades 
                where color_id in (select color_id from colorlikings 
                                     where user_id = ?))
+3
source share
1 answer

, , , , , , , .

, ActiveRecord User.shades, : : . , , .

class User < ActiveRecord::Base
   has_many :color_likings
   has_many :colors, :through => :color_likings

   def get_shades
     colors.collect {|c| c.shades.to_a}.flatten
   end
end

class ColorLiking < ActiveRecord::Base
  belongs_to :user
  belongs_to :color
end

class Color
  has_many :color_likings
  has_many :users, :through => :color_likings  
end

class DiffShade
  belongs_to :color
  belongs_to :shade
end

class Shade
  has_many :diff_shades
  has_many :colors, :through => :diff_shades
end
0

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


All Articles