35

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.

bappelt
  • 418
  • 1
  • 4
  • 13

1 Answers1

57

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

Gopal S Rathore
  • 9,885
  • 3
  • 30
  • 38
bdon
  • 2,068
  • 17
  • 15
  • 5
    Using `&` is deprecated. Use `merge()` instead. See [here](http://stackoverflow.com/questions/7660867/why-using-merge-method-with-scopes-isnt-working-anymore-on-rails-3-1) and [here](https://github.com/rails/rails/commit/66003f596452aba927312c4218dfc8d408166d54) – Jared Beck Jun 03 '12 at 02:06
  • `ActiveRecord#merge` doc is here: https://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-merge – Purplejacket Nov 14 '19 at 00:34