Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在Rails中管理3个多对多模型_Ruby On Rails_Activerecord - Fatal编程技术网

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

Ruby on rails 如何在Rails中管理3个多对多模型,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我遵循的建议是制作一个不同的模型来维护多对多关系。但是,我在提取可传递关系数据时遇到问题 假设有3个模型具有多对多:User Color Shades 我又制作了两个模型: ColorLiking(保持用户颜色)、DiffShades(保持颜色阴影) 问题 现在,如果一切都设置正确…我如何找到属于用户的阴影 我将如何建立这种关系 class User < ActiveRecord::Base has_many :shades, :through=>:diffShades, :s

我遵循的建议是制作一个不同的模型来维护多对多关系。但是,我在提取可传递关系数据时遇到问题

假设有3个模型具有多对多:
User Color Shades

我又制作了两个模型:

ColorLiking(保持用户颜色)、DiffShades(保持颜色阴影)

问题 现在,如果一切都设置正确…我如何找到属于
用户的
阴影

我将如何建立这种关系

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

这是航空代码,可能至少部分错误,但可能有助于将您置于高效的轨道上

长话短说,ActiveRecord不会让您一路找到一个User.shades方法,只需使用各种:has和:beliens调用。但是,编写自己的模型方法来实现这一点并不可怕

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
class用户:颜色
戴上墨镜
颜色。收集{c{c.阴影。到{u a}。展平
结束
结束
类ColorLiking:颜色
结束
DiffShade类
属于:颜色
属于:阴影
结束
类阴影
有很多:不同的色调
有很多:颜色,:通过=>:不同的阴影
结束

随着数据的增长……在循环中进行操作将比SQL慢得多。如果我使用
find\u by\u sql
,那么我可以显式地传递
user\u id
?很好。我绝对不会因为你为此而使用find_by_sql而觉得你不好
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