【问题标题】:getting an error with take in a query Rails在查询 Rails 时出现错误
【发布时间】:2016-04-08 03:02:20
【问题描述】:

我有一个方法如下...

def self.get(code)
 where(code: normalize_code(code)).
 where('coupon_count > 0').
 where('expires_at > Time.now OR expires_at IS NULL').
 take
end

我在“take”行上不断收到错误“参数数量错误(0 代表 1)”。我使用的是 rails 4.0.1 是导致问题还是我遗漏了什么?

编辑查看 4.0.1 http://rails.documentation.codyrobbins.com/4.0.10/classes/ActiveRecord/FinderMethods.html#method-i-take 的文档

我将方法更新为

def self.get(code)
 where(code: normalize_code(code)).
 where('coupon_count > 0').
 where('expires_at > Time.now OR expires_at IS NULL').
 take(1)
end

现在我得到了错误

SyntaxError: Unexpected identifier (16722)

错误在“take”行

-更新-

我的错误在于 coupon_count 的 where 方法。它不在 take 方法中。在接受优惠券之前,我必须弄清楚它不会检查coupon_count 字段的内容。

【问题讨论】:

  • 你能给出确切的堆栈跟踪吗?

标签: ruby-on-rails mongoid take


【解决方案1】:

http://apidock.com/rails/ActiveRecord/FinderMethods/take 文档似乎说take 默认将返回限制为 1。

Person.take # returns an object fetched by SELECT * FROM people LIMIT 1

但是,错误消息告诉我take 需要一个参数。查看此问题 (Arrays in Ruby: Take vs Limit vs First) 答案下方的 cmets,它基本上总结了在 Ruby 1.8.7、1.9.3、2.0.0 或 2.1.0 中没有参数就无法调用 Take。

【讨论】:

【解决方案2】:

既然你只吃一个,不如先试试吧。

【讨论】:

  • 试了一下,得到了我应该说的相同答案或错误
  • 嗯,意外的标识符通常意味着存在语法问题,或者你给它一个来自该方法不在的类的变量。只是出于好奇,主要是因为我从未结束我的 Rails带点的查询,它们应该做什么?
  • 他们将这些方法链接在一起进行 1 个查询
  • 所以也许我的语法是错误的。我想让它说检查字段'coupon_code,如果它大于或= 1'然后得到那个1
猜你喜欢
  • 2011-07-28
  • 2017-01-02
  • 2012-02-22
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多