Damian
Damian

Reputation: 111

Rails scope doesn't return correct data

When I use scope which I prepared in model, rails returns incorrect data.

My Model:

class CurrencyRate < ActiveRecord::Base
    scope :eur_today, -> {where(currency: "eur").where(date: Time.now.in_time_zone.to_date).first}
end

Inforamation from rails console:

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>]>

When I use the same query like in scope, returned data is correct:

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 

Why scope doesn't work correct?

Upvotes: 3

Views: 427

Answers (1)

Ursus
Ursus

Reputation: 30056

Because scopes must return an ActiveRecord::Relation. Get rid of the first call in your scope and use that outside the scope. Why? Because scopes have to be chainable.

Upvotes: 3

Related Questions