views:

453

answers:

2

Is there any way to nest named scopes inside of each other from different models?

Example:

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

Is there any nice way for me to find a company while including employees and spouses like this:
Company.with_employees.with_spouse.find(1)
or is it necessary for me to define another named_scope in Company:
:with_employees_and_spouse, :include => {:employees => :spouse}

In this contrived example, it's not too bad, but the nesting is much deeper in my application, and I'd like it if I didn't have to add un-DRY code redefining the include at each level of the nesting.

A: 

You need define all the time all of your conditions. But you can define some method to combine some 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
shingara
In your with_employees_with_spouse method, you chained together with_employees with the submodel's with_spouse. Was that intended, since that is what I'm looking for a way to do.
WIlliam Jones
yes my exemple is not really great but there are no really good way to do :(
shingara
+1  A: 

You can use default scoping

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

Then this should work. I have not tested it though.

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