如何管理3多到很多车型在Rails中 [英] how to manage 3 many-to-many models in Rails
问题描述
我下面做一个不同型号的 Railscast 咨询维持多到许多
的关系。但是,我无法提取传递关系数据。
想象一下,有3个型号,多到很多:用户< - >颜色和LT; - >百叶窗
我做了2个型号:
ColorLiking(保持用户的LT; - >颜色),DiffShades(保持颜色< - >百叶窗)
问题
现在,如果一切设置正确......我怎么找到百叶窗
是属于用户
?
我将如何建立这种关系?
类用户的LT;的ActiveRecord :: Base的
的has_many:色调,:通过=>:diffShades,:源=> :颜色
结束
上面似乎没有工作...
使用SQL下面的查询将工作:
SELECT * FROM色调
其中id在(选择diffshades shade_id
其中,COLOR_ID中(从colorlikings选择COLOR_ID
其中,USER_ID =?))
这是空中code,它至少部分地错了,但也许有用把你一个高效的轨道上调查
长话短说是的ActiveRecord不会得到你一路到User.shades方法只瓦特/不同:有和:属于调用。但是,这不是太可怕写你自己的模型方法来做到这一点。
类用户的LT;的ActiveRecord :: Base的
的has_many:color_likings
的has_many:颜色,:通过=> :color_likings
高清get_shades
colors.collect {| C | c.shades.to_a} .flatten
结束
结束
类ColorLiking<的ActiveRecord :: Base的
belongs_to的:用户
belongs_to的:颜色
结束
一流的颜色
的has_many:color_likings
的has_many:用户:通过=> :color_likings
结束
类DiffShade
belongs_to的:颜色
belongs_to的:灯罩
结束
一流的阴影
的has_many:diff_shades
的has_many:颜色,:通过=> :diff_shades
结束
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 = ?))
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
这篇关于如何管理3多到很多车型在Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!