Rails 4 - 执行简单查询时未定义的方法“调用" [英] Rails 4 - undefined method `call' when doing a simple query

查看:43
本文介绍了Rails 4 - 执行简单查询时未定义的方法“调用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Rails but this seems pretty straightforward. I have a model called Game generated like this:

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

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

I've loaded the table with some data, and I am trying to fetch all of the rows where is_active is true. I'd like my model to be something like:

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

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

My problem is whenever I try to bind to the Game.active query I get an error. It's the same error in the rails console or if I try to set it to a variable in the controller. The error is:

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

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

When running in the console I see:

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'

推荐答案

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

Rails 4+ requires named scopes to be a lambda and not just a simple Relation.

更换旧版本

scope :active, where(is_active: true)

到 lambda 版本

to the lambda version

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

甚至更短于

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

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

For more information about named scopes and how to pass parameters, I suggest reading about Scopes in the Rails Guide

这篇关于Rails 4 - 执行简单查询时未定义的方法“调用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆