Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a scope from a related model in another scope

I have two related models such as this:

class PartCategory < ActiveRecord::Base 
  has_many :part_types 
  scope :engine, where(:name => 'Engine') 
end 

class PartType < ActiveRecord::Base 
  belongs_to :part_category 
end 

I would like to add a scope to the PartType model such as:

scope :engine_parts, lambda { joins(:part_category).engine } 

But when I try that, I get the following error:

NoMethodError: undefined method `default_scoped?' for ActiveRecord::Base:Class

I don't have a lot of experience with the scope thing, so I am probably missing something fundamental here. Can someone please tell me what it is.

like image 919
bappelt Avatar asked Feb 19 '12 00:02

bappelt


1 Answers

Try this:

scope :engine_parts, lambda { joins(:part_category).merge(PartCategory.engine) } 

Basically, the result of joins(:part_category) is the join of two models, so you can't call .engine on it directly, you need to compose scopes in this manner.

See Here for more

like image 62
bdon Avatar answered Nov 20 '22 09:11

bdon