当我使用我在模型中准备的范围时,rails返回不正确的数据。
我的模特:
class CurrencyRate < ActiveRecord::Base
scope :eur_today, -> {where(currency: "eur").where(date: Time.now.in_time_zone.to_date).first}
end
来自rails控制台的信息:
2.3.0 :011 > CurrencyRate.eur_today
CurrencyRate Load (0.2ms) SELECT "currency_rates".* FROM
"currency_rates" WHERE "currency_rates"."currency" = ? AND
"currency_rates"."date" = ? ORDER BY "currency_rates"."id" ASC LIMIT 1
[["currency", "eur"], ["date", "2017-08-09"]]
CurrencyRate Load (0.2ms) SELECT "currency_rates".* FROM
"currency_rates"
=> #<ActiveRecord::Relation [#<CurrencyRate id: 2, currency: "eur",
sale: 4.248546249999998, purchase: 4.265333125, date: "2017-08-08",
created_at: "2017-08-08 20:52:08", updated_at: "2017-08-08 20:54:10",
sale_percentage_diff: nil, purchase_percentage_diff: nil>]>
当我在范围内使用相同的查询时,返回的数据是正确的:
2.3.0 :012 > CurrencyRate.where(currency: "eur").where(date: Time.now.in_time_zone.to_date).first
CurrencyRate Load (0.2ms) SELECT "currency_rates".* FROM
"currency_rates" WHERE "currency_rates"."currency" = ? AND
"currency_rates"."date" = ? ORDER BY "currency_rates"."id" ASC LIMIT 1
[["currency", "eur"], ["date", "2017-08-09"]]
=> nil
为什么范围不正确?
答案 0 :(得分:2)
因为范围必须返回ActiveRecord::Relation
。摆脱范围内的first
调用,并在范围之外使用它。为什么?因为范围必须是可链接的。