Gro*_*Src 16 ruby-on-rails ruby-on-rails-4.1
我是Rails的新手,但这看起来非常简单.我有一个名为Game生成的模型,如下所示:
rails generate model Game name:string year:integer manufacturer:string notes:string is_active:boolean
Run Code Online (Sandbox Code Playgroud)
我已经装表了一些数据,我试图获取所有地方行is_active是true.我希望我的模型类似于:
class Game < ActiveRecord::Base
scope :active, where(:is_active => 1)
end
Run Code Online (Sandbox Code Playgroud)
我的问题是每当我尝试绑定到Game.active查询时我都会收到错误.这是rails控制台中的相同错误,或者我尝试将其设置为控制器中的变量.错误是:
undefined method `call' for #<Game::ActiveRecord_Relation:0x007ffadb540aa0>
Run Code Online (Sandbox Code Playgroud)
在控制台中运行时,我看到:
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'
Run Code Online (Sandbox Code Playgroud)
spi*_*ann 50
Rails 4+要求命名范围是a lambda而不仅仅是简单范围Relation.
更改旧版本
scope :active, where(is_active: true)
Run Code Online (Sandbox Code Playgroud)
到lambda版本
scope :active, lambda { where(is_active: true) }
Run Code Online (Sandbox Code Playgroud)
甚至更短的
scope :active, -> { where(is_active: true) }
Run Code Online (Sandbox Code Playgroud)
有关命名范围以及如何传递参数的更多信息,我建议您阅读Rails指南中的范围
| 归档时间: |
|
| 查看次数: |
6577 次 |
| 最近记录: |