Ruby on Rails 2.1 - The Finders
Following are the ways to find out records with and without conditions:
Following will find an author with ID 50.
Following will find authors with ID 20, 30 and 40.
Following will find all the authors:
Following will find all the authors with first name alam.
Author.find :all :condition => ["first_name =?", "alam" ]
Following will find first record of the authors with first name alam.
Author.find :first :condition => ["first_name =?", "alam" ]
Options for Finders
You can use following option along with find function.
:order => 'name DESC' Use this option to sort the result in asecing or descending order.
:offset => 20 Starts fetching records from offset 20.
:limit => 20 Returns only 20 records.
:group => 'name' This is equivalent to sql fragment GROUP BY
:joins => LEFT JOIN ...' additional LEFT JOIN (rarely used)
:include => [:account, :friends] This is LEFT OUTER JOIN with these model
:select => [:name, :address] Use this instead of SELECT * FROM
:readonly => true Use this to make objects write protected
Dynamic attribute-based finders
You can use more dynamic functions to fetch values.
If there is a field user_name then you can use following to find records by user name.
If there is a field last_name then you can use following to find records by last name.
If there are fields user_name and password then you can use following to find a record for a given user name and password.