开发者

how to manage 3 many-to-many models in Rails

开发者 https://www.devze.com 2023-01-13 05:47 出处:网络
I\'m following Railscast Advice of making a different model to maintain many-to-many relationships.However, I am having trouble extracting transitive relation data.

I'm following Railscast Advice of making a different model to maintain many-to-many relationships. However, I am having trouble extracting transitive relation data.

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

I've made 2 more models:

ColorLiking (maintains 开发者_StackOverflowUser <-> Color), DiffShades (maintains Color <-> Shades)

Question Now, If everything is set up correctly...how do I find the Shades that belong to a User?

How Will I setup that relationship?

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

above does not seem to work...

Using SQL the below query would work:

select * from shades 
  where id in (select shade_id from diffshades 
                where color_id in (select color_id from colorlikings 
                                     where user_id = ?))


This is air code and probably at least partially wrong, but maybe useful to put you on a productive track investigating.

Long story short is that ActiveRecord won't get you all the way to a User.shades method just w/the various :has and :belongs calls. But it's not too terrible to write your own model method to do it.

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

精彩评论

暂无评论...
验证码 换一张
取 消