Rails ActiveRecord search records between two dates

Yeah, this is simple in Rails.

date = Date.today
start_date = date.at_beginning_of_month
end_date = date.at_end_of_month
Model.where(:created_at => start_date..end_date)

This gives the records created in current month.

This is simple because rails save created_at and updated_at in following format:

created_at: "2018-09-03 09:49:41"

But here in my case,  I had to find the records that are valid for current month. One record is valid only for one day.

In my database the valid date is stored in following format.

valid_date: "2018-09-03"

Here is my solution for this:

date = Date.today
start_date = date.at_beginning_of_month 
end_date = date.at_end_of_month
Model.where( "date(valid_date) BETWEEN ? AND ? ", start_date, end_date)

It will generate following SQL query.

 => "SELECT `models`.* FROM `models` WHERE (date(date) BETWEEN '2018-09-01' AND '2018-09-30' )"
0Shares

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image