Ruby on Rails: Nested Named Areas

Is there a way to nest these areas inside 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 a good way to find a company, including employees and spouses, such as:
Company.with_employees.with_spouse.find(1)
or I need to define another named_scope in the company:
:with_employees_and_spouse, :include => {:employees => :spouse}

In this far-fetched example, this is not so bad, but the nesting in my application is much deeper, and I would like that I would not have to add the NON-SUSHI code, which redefines the inclusion at each nesting level.

+7
include ruby-on-rails activerecord nested
source share
3 answers

You can use the default scope

 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 it should work. I have not tested it though.

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

You need to constantly determine all your conditions. But you can define some method to combine named_scope name

 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 
0
source share

try it

 Company.with_employees.merge( Employees.with_spouse) 
0
source share

All Articles