rico_mac
rico_mac

Reputation: 888

create date between scope in model

I have a model with attributes 'date_starting' and 'date_ending'. I want to create a scope in my model that indicates if the model is within the date start and date end range using Time.now.

something like

scope :activeAtDate, lambda{ |date = Date.today| where("? BETWEEN date_starting AND date_ending", date) }

I used this of a different post but as a newbie, I am having difficulty making this work.

update:

controller

        @current = Guide.activeAtDate

Thanks,

Upvotes: 0

Views: 613

Answers (1)

xlembouras
xlembouras

Reputation: 8295

Your query logic is reversed, you have to find the bounds for each date_* field.
You can do it as follows

scope :active_at_date, lambda {
  where("date_starting < :date and date_ending > :date", date: Date.today )
}

there is no need in providing a parameter to your lambda. Because the parameter is always the same.

If you needed the date to be changeable you would rewrite it as

scope :active_at_certain_date, lambda { |date|
  where("date_starting < :date and date_ending > :date", date: date )
}

Upvotes: 2

Related Questions