我正在跟进铁路广播公司 http://railscasts.com/episodes/47-two-many-to-many制作不同模型进行维护的建议many-to-many
关系。但是,我在提取传递关系数据时遇到问题。
假设有 3 个多对多模型:User <-> Color <-> Shades
我又做了两个模型:
ColorLiking (maintains User <-> Color), DiffShades (maintains Color <-> Shades)
Question现在,如果一切设置正确......我如何找到Shades
属于一个User
?
我将如何建立这种关系?
class User < ActiveRecord::Base
has_many :shades, :through=>: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 不会让您仅通过各种 :has 和 :belongs 调用就一直到达 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)