Ruby on Rails:嵌套命名作用域

8

是否可以在不同的模型中嵌套命名作用域?

例如:

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)
或者我必须在公司中定义另一个named_scope:
:with_employees_and_spouse, :include => {:employees => :spouse}

在这个人为的例子中,情况还不算太糟,但在我的应用程序中,嵌套更深,如果我不得不在每个嵌套级别重新定义include,那就不太好了。

2
据我所知,Rails3的查找器在过滤器链接方面得到了改进。http://m.onkey.org/2010/1/22/active-record-query-interface - clyfe
3个回答

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]

1
我建议避免使用default_scope。它很难在需要时绕过它,而且它会比你想象的更经常地妨碍你。 - Ben Scheirman
我会将其优化为仅使用default_scope进行排序,而不是使用它来细化或限制查询返回的记录。 - Michael Durrant

0

你需要始终定义你所有的条件。但你可以定义一些方法来组合一些命名作用域


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进行了链式操作。由于这正是我想要做的,所以这是否是有意为之呢? - William Jones
是的,我的例子并不是很好,但是没有真正好的方法可以做到 :( - shingara

0

试试这个

Company.with_employees.merge( Employees.with_spouse)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接