views:

41

answers:

2

HI

whats the best way to implement a simple search in rails to retrieve all models with the same date?

e.g retrieve all customer with birthday date on 23-10-1975, which will be of a date format.

i.e

  create_table "customer", :force => true do |t|
    t.string   "f_name"
    t.string   "m_name"
    t.string   "l_name"
    t.date     "date_of_birth" 
end
+3  A: 

I presume you want to congratulate all users that have their birthday today? Well, I'm not on a dev-machine now, so I can't test it, but I would go for something like this:

@bday_customers = Customer.find(:all, :conditions => { :birthday => Date.today } )

or even

@bday_customers = Customer.find(:all, :conditions => { :birthday => (Date.today)..(Date.today + 2.weeks) } )

This will cause your database to do the work as it its optimised for such searches.

Rock
i want to be able to search customers in the index page by date of birth. i.e retrive all customers with date of birth bla bla bla etc. using a date_select in the view?
Mo
Well, then simply replace the 'Date.today' with the given params value from the date_select. But unless you want to play a lottery when searching for just one specific date, I suggest the range option that I used in my second example.
Rock
the date format i get back from my date_select is a hash like so {"(1i)"=>"2010", "(2i)"=>"8", "(3i)"=>"16"}, how can i convert that in to a Date format so i can use it in the :condition? thanks
Mo
+1  A: 

Assuming date is a string of the form 23-10-1975 then something like this;

Customer.all(:conditions => { :date_of_birth => Date.strptime(date, '%d-%m-%Y') })
bjg
sorry, my question was very vague, i updated the question. im not too familiar with rails, but the date is not a string format. its date.
Mo
@Mo I understand that the database field is a date and not a string. The string that I was talking about was the format you will get from your view through the `date_select` which the user submits the form
bjg
@bjg Sorry i didn't really know what you meant. my bad. thanks for the answer.
Mo