Ruby on Rails:嵌套命名范围

Posted

技术标签:

【中文标题】Ruby on Rails:嵌套命名范围【英文标题】:Ruby on Rails: Nested named scopes 【发布时间】:2011-01-24 06:42:07 【问题描述】:

有没有办法将不同模型的命名范围相互嵌套?

例子:

class Company
  has_many :employees
  named_scope :with_employees, :include => :employees
end
class Employee
  belongs_to :company
  belongs_to :spouse
  named_scope :with_spouse, :include => :spouse
end
class Spouse
  has_one :employee
end

我有什么好的方法可以找到一家公司,同时包括这样的员工和配偶:Company.with_employees.with_spouse.find(1) 还是我需要在 Company 中定义另一个 named_scope::with_employees_and_spouse, :include => :employees => :spouse

在这个人为的例子中,它并不算太糟糕,但是我的应用程序中的嵌套要深得多,如果我不必添加 un-DRY 代码来重新定义嵌套的每个级别的包含,我会喜欢它.

【问题讨论】:

据我所知 rails3 finders m.onkey.org/2010/1/22/active-record-query-interface 改进了过滤器链接区域。 【参考方案1】:

您可以使用默认范围

class Company
  default_scope :include => :employees
  has_many :employees
end

class Employee
  default_scope :include => :spouse
  belongs_to :company
  belongs_to :spouse
end

class Spouse
  has_one :employee
end

那么这应该可以工作。不过我还没有测试过。

Company.find(1)          # includes => [:employee => :spouse]

【讨论】:

我建议远离 default_scope。当你需要的时候很难回避,而且它比你想象的更频繁。 我会将其细化为仅使用 default_scope 进行排序,而不是使用它来细化或限制查询返回的记录。【参考方案2】:

您需要始终定义所有条件。但是你可以定义一些方法来组合一些named_scope


class Company
  has_many :employees
  named_scope :with_employees, :include => :employees
  named_scope :limit, :lambda|l| :limit => l 

  def with_employees_with_spouse
    with_employees.with_spouse
  end

  def with_employees_with_spouse_and_limit_by(limit)
    with_employees_with_spouse.limit(limit)
  end

end
class Employee
  belongs_to :company
  belongs_to :spouse
  named_scope :with_spouse, :include => :spouse
end
class Spouse
  has_one :employee
end

【讨论】:

在您的 with_employees_with_spouse 方法中,您将 with_employees 与子模型的 with_spouse 链接在一起。这是故意的吗,因为这就是我正在寻找的方法。 是的,我的例子不是很好,但是没有很好的方法:(【参考方案3】:

试试这个

Company.with_employees.merge( Employees.with_spouse)

【讨论】:

以上是关于Ruby on Rails:嵌套命名范围的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 ruby​​ on rails 生成人类可读的时间范围

Ruby on rails:仅从两列范围内获取数据

Ruby on Rails,将项目范围的单引号转换为双引号

作物哈希结构:Ruby on rails

ruby-on-rails - 嵌套资源问题

无法在 gem Devise 中调整控制器,ruby on rails 4