Marcos R. Guevara
Marcos R. Guevara

Reputation: 6388

Scope with days period works from the last deploy date

I have a scope on a booking model, that takes bookings into the current period of 15 days. it works, so, in production, after one day i seen that not works, on the log applies the scope filter from the moment deployment was done.

First, scope looked as this:

scope :current_availables, where(date: Date.today..Date.today+14.days )

And now the scope looks like this

scope :current_availables, where(date: Date.current.beginning_of_day..Date.current+14.days )

What is happening?

Upvotes: 2

Views: 590

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33470

This is from the Rails 3.1.0 documentation:

Note that scopes defined with scope will be evaluated when they are defined, rather than when they are used. For example, the following would be incorrect:

class Post < ActiveRecord::Base
  scope :recent, where('published_at >= ?', Time.now - 1.week)
end

The example above would be ‘frozen’ to the Time.now value when the Post class was defined, and so the resultant SQL query would always be the same. The correct way to do this would be via a lambda, which will re-evaluate the scope each time it is called:

class Post < ActiveRecord::Base
  scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) }
end

So, you can try updating your scope to use a lambda as the second argument instead of just the where:

scope :current_availables, -> { where(date: Date.current.beginning_of_day..Date.current+14.days) }

(Not sure if you can use -> if not do lambda)

You can also use 14.days.from_now instead of adding the 14 days to Date.current.

Upvotes: 4

Related Questions