如何在Rails中管理3个多对多模型

我正在遵循Railscast建议制作一个不同的模型来维护many-to-many关系。 但是,我无法提取传递关系数据。

想象一下,有3个模型具有多对多: User Color Shades

我又制作了两个型号:

ColorLiking (maintains User Color), DiffShades (maintains Color Shades)

问题现在,如果一切设置正确…如何找到属于UserShades

我将如何建立这种关系?

 class User :diffShades, :source => :color end 

上面似乎不起作用……

使用SQL,以下查询将起作用:

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

这是航空代码,可能至少部分错误,但可能有助于您进行富有成效的调查。

简而言之,ActiveRecord不会让你一直到User.shades方法只是w /各种:has和:属于调用。 但是编写自己的模型方法来实现它并不是太糟糕。

 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