Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.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:用于获取与集合关联的集合的查询_Ruby On Rails_Activerecord_Associations_Has Many Through - Fatal编程技术网

Ruby on rails Rails:用于获取与集合关联的集合的查询

Ruby on rails Rails:用于获取与集合关联的集合的查询,ruby-on-rails,activerecord,associations,has-many-through,Ruby On Rails,Activerecord,Associations,Has Many Through,所以我有四门课: class User < ActiveRecord::Base has_many :water_rights end class WaterRight < ActiveRecord::Base belongs_to :user has_many :place_of_use_area_water_rights has_many :place_of_use_areas, through: :place_of_use_area_water_rights

所以我有四门课:

class User < ActiveRecord::Base
  has_many :water_rights
end

class WaterRight < ActiveRecord::Base
  belongs_to :user
  has_many :place_of_use_area_water_rights
  has_many :place_of_use_areas, through: :place_of_use_area_water_rights
end

class PlaceOfUseAreaWaterRight < ActiveRecord::Base
  belongs_to :place_of_use_area
  belongs_to :water_right
end

class PlaceOfUseArea < ActiveRecord::Base
  has_many :place_of_use_area_water_rights
  has_many :water_rights, through: :place_of_use_area_water_rights
end

这是可行的,但它对每个水权都进行了新的查询。我正在寻找一种方法来进行一次查询以获取关联的placeOfSeas集合。

您只想在一次查询中获取所有关联的placeOfSeas对象,对吗

如果是这样的话,Rails有一个非常简单的解决方案:

PlaceOfUseArea.joins(:water_wights).uniq

如果您想了解更多信息,请阅读更多。

是的,但我只想为特定用户的水权获得Seareas的位置。placeOfSearea.joins:water\u rights.wherewater\u rights:{user\u id:user.first.id}.uniq我猜类似的东西会有用吗?还有,有没有办法只在ID列上使用uniq?我有一个JSON列,它似乎抛出了以下错误:PG::UndefinedFunction:error:无法识别JSON类型的相等运算符。我最终使用了以下查询:placeOfSearea.joins:water_rights.wherewater_rights:{user_id:user.id}.group'place_of_use_areas.id',它得到了我需要的东西。谢谢你给我指明了正确的方向!不客气!关于uniq还有一个提示:您可以使用&block。例如:placeOfSearea.joins:water_wights.uniq{{| result | result.id}。你可以读更多的啊,太好了!我总是在最后关头。我甚至没有想到我会使用数组方法。再次感谢!
PlaceOfUseArea.joins(:water_wights).uniq