Sergio Nekora
Sergio Nekora

Reputation: 319

Rails, date search query from a datetime field. Why this one does not work?

I am new in this world of Rails, so sorry if the mistake is too obvious.

I am building a search form. I managed to compare strings. However I am struggling with dates.

This is in the form:

= select_datetime Date.today, :prefix => :search_start_date

This is the query I am trying (note:start_date in a valid column in Events)

 @events = @events.where("start_date > ?", "%#{params[:search_start_date]}%")

Because one is a date and the other a datetime I though I had to cast them. However nothing I have tried have worked.

Any suggestions? Thanks

Upvotes: 0

Views: 2728

Answers (3)

Vik
Vik

Reputation: 5961

Try to use parse :

 @events = @events.where("start_date > ?", "%#{Date.parse(params[:search_start_date])}%") if !params[:search_start_date].nil?

Upvotes: 0

CupraR_On_Rails
CupraR_On_Rails

Reputation: 2489

You can put your params in a Time object :

@time = Time.new(params[:search_start_date][:year], params[:search_start_date][:month],params[:search_start_date][:day] , params[:search_start_date][:hour], params[:search_start_date][:minute])
@events = Event.where("start_date > ?", @time)

It should work. However you should set start_date with a datetime type. Indeed If you have an event with the date April 17, 2012 and you are looking for @events started after April 17, 2012 at 9:00 the event will not displayed. Only event starting the April 18 and after will be displayed.

Upvotes: 1

Kashiftufail
Kashiftufail

Reputation: 10885

Can you try this it give you better results

 @time = params[:search_start_date]+" "+"00:00:00"

 @events = @events.where("start_date > ?", @time)

Try it and it give you reult with time greater than 00:00:00

Upvotes: 0

Related Questions