I 开发者_运维技巧am trying to filer records based on date from created_at
.
For this I am passing from_date
and to_date
from date-picker in Date Format (e.g. "%y/%m/%d"
).
Please help me with how to write query in the controller to fetch the records between dates.
@users = User.where(['created_at = ? and created_at = ?',from_date,to_date])
Thanks.
You can use the range syntax, looks cleaner:
@users = User.where(:created_at => start_date.to_time..end_date.to_time)
@users = User.where("created_at between (?) and (?)", start_date, end_date)
or
@users = User.where("created_at >= (?) AND created_at <= (?)", start_date, end_date)
or in worst case
@users = User.where("created_at between (?) and (?)", start_date.to_time, end_date.to_time)
The best solution is this, it will wrap the dates from 00:00:00 hour and 23:59:59
@users = User.where(created_at: from_date.beginning_of_day..to_date.end_of_day)
This will work 100%.
starting_date_month = params[:date_from].split("-")[0].to_i
starting_date_year = params[:date_from].split("-")[1].to_i
ending_date_month = params[:date_to].split("-")[0].to_i
ending_date_year = params[:date_to].split("-")[1].to_i
records = self.where("extract(month from created_at) BETWEEN ? AND ? AND extract(year from created_at) between ? AND ? AND status = ? AND v_id = ?", starting_date_month,ending_date_month,starting_date_year,ending_date_year,6,params[:v_id])
精彩评论