Search between two dates in rails activerecord

I get the date in my parameters and go through the database to see if the date is between the start date and the end date. My code is as follows.

    date = params[:date]

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

      

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

I don't understand what I am doing wrong.

+3


source to share


3 answers


Try This is a rails format for validating a date between two dates.

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 an array of campaigns created on the given date range.

Hope this helps.

+13


source


You should look like this (note the missing square brackets you included in your query.

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

      

This will return an array of campaigns, with the date between start_date and end_date. So you can't just tell record.id

, because the record is actually an array of campaign objects.



Instead, try viewing the result to access individual items in the campaign array.

record.each do |record_object|  
    # perform some action on each record_object here
end

      

+5


source


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

      

Hope this helps.

+3


source







All Articles