Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 240
Damian Avatar asked Jul 26 '26 05:07

Damian


1 Answers

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.

like image 141
Ursus Avatar answered Jul 28 '26 04:07

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!