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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With