Copyright © tutorialspoint.com

Ruby on Rails - Finders

previous

Following are the ways to find out records with and without conditions:

Following will find an author with ID 50.

Author.find(50)

Following will find authors with ID 20, 30 and 40.

Author.find([20,30, 40])

Following will find all the authors:

Author.find :all

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.

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.

Person.find_by_user_name(user_name)

If there is a field last_name then you can use 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 following to find a record for a given user name and password.

Person.find_by_user_name_and_password(user_name, password)
previous

Copyright © tutorialspoint.com