| Module | ActiveRecord::FinderMethods |
| In: |
lib/active_record/relation/finder_methods.rb
|
Returns true if a record exists in the table that matches the id or conditions given, or false otherwise. The argument can take five forms:
For more information about specifying conditions as a Hash or Array, see the Conditions section in the introduction to ActiveRecord::Base.
Note: You can‘t pass in a condition as a string (like name = ‘Jamie‘), since it would be sanitized and then queried against the primary key column, like id = ‘name = \’Jamie\’‘.
Person.exists?(5)
Person.exists?('5')
Person.exists?(:name => "David")
Person.exists?(['name LIKE ?', "%#{query}%"])
Person.exists?
Find operates with four different retrieval approaches:
All approaches accept an options hash as their last parameter.
# find by id
Person.find(1) # returns the object for ID = 1
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)
Note that returned records may not be in the same order as the ids you provide since database rows are unordered. Give an explicit :order to ensure the results are sorted.
# find first
Person.first # returns the first object fetched by SELECT * FROM people
Person.where(["user_name = ?", user_name]).first
Person.where(["user_name = :u", { :u => user_name }]).first
Person.order("created_on DESC").offset(5).first
# find last
Person.last # returns the last object fetched by SELECT * FROM people
Person.where(["user_name = ?", user_name]).last
Person.order("created_on DESC").offset(5).last
# find all
Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
Person.where(["category IN (?)", categories]).limit(50).all
Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
Person.offset(10).limit(10).all
Person.includes([:account, :friends]).all
Person.group("category").all
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