使用另一个范围中相关模型的范围

bap*_*elt 29 activerecord ruby-on-rails

我有两个相关的模型,如:

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

class PartType < ActiveRecord::Base 
  belongs_to :part_category 
end 
Run Code Online (Sandbox Code Playgroud)

我想在PartType模型中添加一个范围,例如:

scope :engine_parts, lambda { joins(:part_category).engine } 
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这个时,我收到以下错误:

NoMethodError:未定义的方法`default_scoped?' 对于ActiveRecord :: Base:Class

我没有很多关于范围的经验,所以我可能在这里缺少一些基本的东西.有人可以告诉我它是什么.

小智 49

试试这个:

scope :engine_parts, lambda { joins(:part_category).merge(PartCategory.engine) } 
Run Code Online (Sandbox Code Playgroud)

基本上,结果joins(:part_category)是两个模型的连接,所以你不能.engine直接调用它,你需要以这种方式组合范围.

请看这里了解更多

  • 使用`&`已弃用.请改用"merge()".见[here](http://stackoverflow.com/questions/7660867/why-using-merge-method-with-scopes-isnt-working-anymore-on-rails-3-1)和[here](https: //github.com/rails/rails/commit/66003f596452aba927312c4218dfc8d408166d54) (5认同)