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

∥☆過路亽.° 提交于 2019-12-10 19:19: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.

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

I've made 2 more models:

ColorLiking (maintains User <-> 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 = ?))

回答1:


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


来源:https://stackoverflow.com/questions/3568528/how-to-manage-3-many-to-many-models-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!