简体   繁体   中英

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.

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.

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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM