Monday, October 24, 2011

Finding more than one record easily in Rails (with Ruby)

In order to find records from the database matching certain criteria, one can use the Rails find(:all) construct, passing to it all the required conditions, in a manner like this :

objects = Model.find(:all, :conditions => { :field1 => "value1", :field2 => value2, ... })


But this becomes much of an overkill if you want to specify only 2/3 conditions.

Let's suppose, the model is called Users and 2 of its fields, user_name and user_email are to be used in the condition.



We could rather use a shorthand form:


objects = Users.find_by_user_name_and_user_email("ABCD","abcd@efgh.com")


Note that the order of values passed is picked up to match the field names mentioned in the calling method.


This has the same result as the more conventional:


objects = Users.find(:all, :conditions => {:user_name => "ABCD", :user_email => "ABCD@efgh.com"})


For one thing it reduces the need to type all the braces and the => operator and can be used effectively to reduce the typing and make code more readable.


The short-hand can be extended with as many fields but is not suggested as then it makes code all the more difficult to read.



No comments:

Post a Comment