
- Learning Ruby on Rails
- Rails 2.1 Home
- Rails 2.1 Introduction
- Rails 2.1 Installation
- Rails 2.1 Framework
- Rails 2.1 Dir Structure
- Rails 2.1 Examples
- Rails 2.1 Database Setup
- Rails 2.1 Active Records
- Rails 2.1 Migrations
- Rails 2.1 Controllers
- Rails 2.1 Views
- Rails 2.1 Layouts
- Rails 2.1 Scaffolding
- Rails 2.1 and AJAX
- Rails 2.1 Uploads Files
- Rails 2.1 Sends Emails
- Advanced Ruby on Rails 2.1
- Rails 2.1 RMagick Guide
- Rails 2.1 Basic HTTP Auth
- Rails 2.1 Error Handling
- Rails 2.1 Routes System
- Rails 2.1 Unit Testing
- Advanced Ruby on Rails 2.1
- Rails 2.1 Tips & Tricks
- Quick Reference Guide
- Quick Reference Guide
- Ruby on Rails 2.1 Useful Resources
- Ruby on Rails 2.1 - Resources
- Ruby on Rails 2.1 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ruby on Rails 2.1 - The Finders
Following are the ways to find out records with and without conditions −
The following code will find an author with ID 50.
Author.find(50)
The following code will find authors with ID 20, 30 and 40.
Author.find([20,30, 40])
The following code will find all the authors −
Author.find :all
The following code will find all the authors with first name alam.
Author.find :all :condition => ["first_name =?", "alam" ]
The following code will find the first record of the authors with first name alam.
Author.find :first :condition => ["first_name =?", "alam" ]
Options for Finders
You can use the following options along with the find function.
:order => 'name DESC' Use this option to sort the result in ascending 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 the following to find records by username.
Person.find_by_user_name(user_name)
If there is a field last_name, then you can use the following to find records by last name.
Person.find_all_by_last_name(last_name)
If there are fields user_name and password, then you can use the following to find a record for a given username and password.
Person.find_by_user_name_and_password(user_name, password)