Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Nested named scopes

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.

like image 250
William Jones Avatar asked Mar 05 '10 19:03

William Jones


1 Answers

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]
like image 187
Ram on Rails React Native Avatar answered Nov 07 '22 06:11

Ram on Rails React Native