嵌套查询的子集

时间:2012-03-01 18:39:52

标签: ruby-on-rails

我不太清楚甚至要搜索什么才能解决这个具体问题。 所以这里......

我目前的设计:

User < AR
  has_many :items
  has_many :projects

Project < AR
  has_many :groups

Group < AR
  has_many :items

给定@project@user如何获取项目的组(@project.groups),但这些组仅包含items给定的@user?< / p>

这似乎应该在模型中处理,而不是作为控制器逻辑,但我不确定最好的Rails方式是做什么的。我调查了范围和定制查找器,但似乎不必要地复杂化。也许这是模型之间关系的一个缺陷。

编辑:也许这有帮助?

User < AR
  has_many :items
  has_and_belongs_to_many :projects

Project < AR
  has_many :groups
  has_and_belongs_to_many :users

Group < AR
  has_many :items

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找has_many:通过:

class User < ActiveRecord::Base
  has_many :projects
  has_many :groups, :through => :projects
  has_many :items, :through => :groups
end

class Project < ActiveRecord::Base
  has_many :groups
end

class Group < ActiveRecord::Base
  has_many :items
end

然后你可以打电话:

@user.items

获取给定用户的所有项目。

请注意,嵌套的has_many:throughs仅在Rails 3.1之后起作用;否则,你可能不得不写一个方法!

答案 1 :(得分:0)

这有一点原始SQL,但应该可以工作:

def Project
  def groups_for_user u
    self.groups.select("DISTINCT groups.*").join(:items).where("items.user_id = ?,u.id)
  end
end

"DISTINCT groups.*"的原因是为了防止结果重复,因为您正在加入较低级items表。

相关问题