Rails 4 - 执行简单查询时未定义的方法`call'

问题描述 投票:16回答:1

我是Rails的新手,但这看起来非常简单。我有一个名为Game的模型生成如下:

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

我已经加载了包含一些数据的表,我正在尝试获取is_activetrue的所有行。我希望我的模型类似于:

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'
ruby-on-rails ruby-on-rails-4.1
1个回答
50
投票

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

更改旧版本

scope :active, where(is_active: true)

到lambda版本

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

甚至更短的

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

有关命名范围以及如何传递参数的更多信息,我建议阅读有关Scopes in the Rails Guide的内容

© www.soinside.com 2019 - 2024. All rights reserved.