Topic: find :all, :conditions => using datetime

Hi there,

I'm new at ruby on rails and can't find the correct way to work with dates and datetimes as part of the condition of a find.

I want to find all ActiveRecords between two datetimes (start_date and end_date):

bugs = Bug.find :all,
                :order => 'id DESC',
        :conditions => 'status_id = "3" AND date_fixed > ' + start_date + ' AND date_fixed <= ' + end_date + ' AND product_id = ' + params[:id]

Is there a direct way to pass dates/datetimes onto a query for comparison?
Is the way that I've written the condition above ok, is there a preferrred method to pass multiple conditions?

Any help greatly appreciated.



Re: find :all, :conditions => using datetime

I found this which seems to do the job, although I thought there would be a way to do it without me having to convert the datetime value to a database datetime.

bugs = Bug.find :all, :order => 'id DESC',
    :conditions => 'status_id = "3" AND date_fixed > "' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '" AND date_fixed <= "' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '" AND product_id = ' + params[:id]

If anyone has a more elegant way of doing this, please let me know anyway.



Re: find :all, :conditions => using datetime

Try this

bugs = Bug.find :all, :order => 'id DESC',
    :conditions => ['status_id = "3" AND date_fixed > ? AND date_fixed <= ? AND product_id = ?', start_date, end_date, params[:id]]

There's always a more elegant way with Rails wink

Re: find :all, :conditions => using datetime

Unbelievable! And I thought I tried all different combinations of the '?' substitution...
It's hard being a newbie...

Your solution worked perfectly and it is so much more elegant.

Thank you thabenksta!


Re: find :all, :conditions => using datetime

Dont worry we are all new once smile  The good this is from my experience we have a fairly good community here, although I probably need to start answering more things than asking smile

Last edited by Catharsis (2006-11-23 07:31:48)

Re: find :all, :conditions => using datetime

Hi, I am a beginner from Argentina..and these posts were useful for me.
Thanks for sharing them.