Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching between two dates in rails activerecord

I'm receiving a date in my parameters and searching the database to see if the date falls between start date and end date. My code is the following.

    date = params[:date]

    record = Campaign.where(['start_date < ? AND end_date > ?', date, date])

This only returns each records name. But when I try to access the full record, like its id, rails throws an error.

I don't understand what I'm doing wrong.

like image 327
Brogrammer Avatar asked Jul 13 '15 02:07

Brogrammer


3 Answers

Try This this is the rails format to check date between two date.

start_date = params[:start_date].to_date.beginning_of_day
end_date = params[:end_date].to_date.end_of_day
records = Campaign.where(:created_at => start_date..end_date)

It will return array of campaigns created in given date range.

Hope it will helps.

like image 102
milind phirake Avatar answered Nov 16 '22 09:11

milind phirake


You're query should look like this (note the absence of the square brackets which you include in your query.

date = params[:date]
record = Campaign.where('start_date < ? AND end_date > ?', date, date)  

This will return an array of Campaigns where the date falls between it's start_date and end_date. Therefore, you could not just say record.id because record is actually an array of Campaign objects.

Instead, try looping through the result to access the individual elements in the array of campaigns.

record.each do |record_object|  
    # perform some action on each record_object here
end
like image 26
Mike Avatar answered Nov 16 '22 10:11

Mike


Campaign.where(
  "created_at >= :start_date AND created_at <= :end_date",
  { start_date: params[:start_date],
    end_date: params[:end_date]}
)

Hope it will helps.

like image 6
Venkatesh Dhanasekaran Avatar answered Nov 16 '22 09:11

Venkatesh Dhanasekaran