find

find(*args)
Instance Public methods

Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key is an integer, find by id coerces its arguments using to_i.

Person.find(1)          # returns the object for ID = 1
Person.find("1")        # returns the object for ID = 1
Person.find("31-sarah") # returns the object for ID = 31
Person.find(1, 2, 6)    # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17])    # returns an array for objects with IDs in (7, 17)
Person.find([1])        # returns an array for the object with ID = 1
Person.where("administrator = 1").order("created_on DESC").find(1)

ActiveRecord::RecordNotFound will be raised if one or more ids are not found.

NOTE: The returned records may not be in the same order as the ids you provide since database rows are unordered. You'd need to provide an explicit order option if you want the results are sorted.

Find with lock

Example for find with a lock: Imagine two concurrent transactions: each will read person.visits == 2, add 1 to it, and save, resulting in two saves of person.visits = 3. By locking the row, the second transaction has to wait until the first is finished; we get the expected person.visits == 4.

Person.transaction do
  person = Person.lock(true).find(1)
  person.visits += 1
  person.save!
end

Variations of find

Person.where(name: 'Spartacus', rating: 4)
# returns a chainable list (which can be empty).

Person.find_by(name: 'Spartacus', rating: 4)
# returns the first item or nil.

Person.where(name: 'Spartacus', rating: 4).first_or_initialize
# returns the first item or returns a new instance (requires you call .save to persist against the database).

Person.where(name: 'Spartacus', rating: 4).first_or_create
# returns the first item or creates it and returns it, available since Rails 3.2.1.

Alternatives for find

Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
# returns a boolean indicating if any record with the given conditions exist.

Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
# returns a chainable list of instances with only the mentioned fields.

Person.where(name: 'Spartacus', rating: 4).ids
# returns an Array of ids, available since Rails 3.2.1.

Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
# returns an Array of the required fields, available since Rails 3.1.
doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.