Arif Arif - 1 year ago 176
Ruby Question

Rails: Query ActiveRecord by month and year

In my rails project there is a search page that contains a drop-down with date range values separated by (-). The options of drop-down are like:

Jan,2014 - March,2014
April,2014 - Jun,2014
Oct,2014 - Dec,2014

User can select one of these date ranges and only those records will be shown that fall in selected date range. The field to filter by is
with is a timestamp field.

So I want something like this:

filter = params[:filter].split("-")
@posts = Post.where(start_date: filter[0]..filter[1])

But in params I only get month and year. How can I parse these values so that the above query works?

Answer Source

Hey you can try to parse string to date using Date.strptime

filter = params[:filter].split(" - ") 

Convert string to date using strptime

st_date = Date.strptime(filter[0],"%B,%Y")
end_date = Date.strptime(filter[1],"%B,%Y")

Create daterange as beginning of first month to end of second month

date_range = st_date.beginning_of_month..end_date.end_of_month

@posts = Post.where(:start_date =>  date_range)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download