16

我是 Rails 的新手,但这似乎很简单。我有一个名为Gamegenerate 的模型,如下所示:

rails generate model Game name:string year:integer manufacturer:string notes:string is_active:boolean

我已经在表格中加载了一些数据,并且我正在尝试获取is_activeis的所有行true。我希望我的模型是这样的:

class Game < ActiveRecord::Base
  scope :active, where(:is_active => 1)
end

我的问题是每当我尝试绑定到Game.active查询时都会出错。Rails 控制台中的相同错误,或者如果我尝试将其设置为控制器中的变量。错误是:

undefined method `call' for #<Game::ActiveRecord_Relation:0x007ffadb540aa0>

在控制台中运行时,我看到:

irb(main):001:0> Game.active
NoMethodError:   Game Load (0.2ms)  SELECT `games`.* FROM `games`  WHERE `games`.`is_active` = 1
undefined method `call' for #<Game::ActiveRecord_Relation:0x007fcdca66b800>
    from /home/dcain/.rbenv/versions/2.1.1/lib/ruby/gems/2.1.0/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:136:in `method_missing'
4

1 回答 1

50

Rails 4+ 要求命名范围是 alambda而不仅仅是简单的Relation.

更换旧版本

scope :active, where(is_active: true)

到 lambda 版本

scope :active, lambda { where(is_active: true) }

甚至更短于

scope :active, -> { where(is_active: true) }

有关命名范围和如何传递参数的更多信息,我建议阅读Rails 指南中的范围

于 2014-04-28T10:04:25.323 回答