module ActiveRecord::FinderMethods
Константы
- ONE_AS_ONE
Публичные методы экземпляра
# File activerecord/lib/active_record/relation/finder_methods.rb, line 277
def exists?(conditions = :none)
if Base === conditions
conditions = conditions.id
ActiveSupport::Deprecation.warn(" You are passing an instance of ActiveRecord::Base to `exists?`.
Please pass the id of the object by calling `.id`
".squish)
end
return false if !conditions
relation = apply_join_dependency(self, construct_join_dependency)
return false if ActiveRecord::NullRelation === relation
relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)
case conditions
when Array, Hash
relation = relation.where(conditions)
else
unless conditions == :none
relation = relation.where(primary_key => conditions)
end
end
connection.select_value(relation, "#{name} Exists", relation.arel.bind_values + relation.bind_values) ? true : false
end Возвращает true если запись существует в таблице, которая соответствует id или заданным условиям, или false в противном случае. Аргумент может принимать шесть форм:
-
Integer - Находит запись с этим первичным ключом.
-
String - Находит запись с первичным ключом, соответствующим этой строке (например,
'5'). -
Array - Находит запись, которая соответствует этим условиям в стиле
find(например,['name LIKE ?', "%#{query}%"]). -
Hash - Находит запись, которая соответствует этим условиям в стиле
find(например,{name: 'David'}). -
false- Всегда возвращаетfalse. -
Без аргументов - Возвращает
falseесли таблица пуста,trueв противном случае.
Для получения дополнительной информации о задании условий в виде хэша или массива, см. раздел «Условия» во введении к ActiveRecord::Base.
Примечание: Нельзя передать условие в виде строки (например, name =
'Jamie'), так как оно будет очищено, а затем выполнен запрос к столбцу первичного ключа, например id = 'name =
\'Jamie\''.
Person.exists?(5)
Person.exists?('5')
Person.exists?(['name LIKE ?', "%#{query}%"])
Person.exists?(id: [1, 4, 8])
Person.exists?(name: 'David')
Person.exists?(false)
Person.exists?
# File activerecord/lib/active_record/relation/finder_methods.rb, line 224 def fifth find_nth(4, offset_index) end
Находит пятую запись. Если порядок не определен, он будет упорядочен по первичному ключу.
Person.fifth # returns the fifth object fetched by SELECT * FROM people
Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7)
Person.where(["user_name = :u", { u: user_name }]).fifth
# File activerecord/lib/active_record/relation/finder_methods.rb, line 230 def fifth! find_nth! 4 end
То же самое, что и fifth, но вызывает ActiveRecord::RecordNotFound если запись не найдена.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 67
def find(*args)
if block_given?
to_a.find(*args) { |*block_args| yield(*block_args) }
else
find_with_ids(*args)
end
end Поиск по id - Это может быть как конкретный id (1), список id (1, 5, 6), так и массив id ([5, 6, 10]). Если запись не может быть найдена для всех указанных id, то будет вызвана ошибка RecordNotFound. Если первичный ключ является целым числом, поиск по id приводит свои аргументы к нужному типу с помощью 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 будет вызвана, если один или несколько id не найдены.
ПРИМЕЧАНИЕ: Возвращаемые записи могут быть не в том же порядке, что и предоставленные вами id, поскольку строки базы данных не упорядочены. Вам потребуется указать явный параметр order, если вы хотите, чтобы результаты были отсортированы.
Поиск с блокировкой
Пример поиска с блокировкой: Представьте две параллельные транзакции: каждая будет читать person.visits == 2, добавлять к нему 1 и сохранять, что приводит к двум сохранениям person.visits = 3. Блокируя строку, вторая транзакция должна ждать завершения первой; мы получаем ожидаемый person.visits == 4.
Person.transaction do person = Person.lock(true).find(1) person.visits += 1 person.save! end
Варианты 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.
Альтернативы для 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.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 83 def find_by(*args) where(*args).take rescue RangeError nil end
Находит первую запись, соответствующую указанным условиям. Нет неявного порядка, поэтому, если порядок важен, вы должны указать его сами.
Если запись не найдена, возвращает nil.
Post.find_by name: 'Spartacus', rating: 4 Post.find_by "published_at < ?", 2.weeks.ago
# File activerecord/lib/active_record/relation/finder_methods.rb, line 91
def find_by!(*args)
where(*args).take!
rescue RangeError
raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value"
end Как find_by, за исключением того, что если запись не найдена, возникает ошибка ActiveRecord::RecordNotFound.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 123
def first(limit = nil)
if limit
find_nth_with_limit(offset_index, limit)
else
find_nth(0, offset_index)
end
end Находит первую запись (или первые N записей, если указан параметр). Если порядок не определен, он будет упорядочен по первичному ключу.
Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1
Person.where(["user_name = ?", user_name]).first
Person.where(["user_name = :u", { u: user_name }]).first
Person.order("created_on DESC").offset(5).first
Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3
# File activerecord/lib/active_record/relation/finder_methods.rb, line 133 def first! find_nth! 0 end
То же самое, что и first, но вызывает ActiveRecord::RecordNotFound если запись не найдена. Обратите внимание, что first! не принимает аргументов.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 240 def forty_two find_nth(41, offset_index) end
Находит сорок вторую запись. Также известен как доступ к «reddit». Если порядок не определен, он будет упорядочен по первичному ключу.
Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44)
Person.where(["user_name = :u", { u: user_name }]).forty_two
# File activerecord/lib/active_record/relation/finder_methods.rb, line 246 def forty_two! find_nth! 41 end
То же самое, что и forty_two, но вызывает ActiveRecord::RecordNotFound если запись не найдена.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 208 def fourth find_nth(3, offset_index) end
Находит четвертую запись. Если порядок не определен, он будет упорядочен по первичному ключу.
Person.fourth # returns the fourth object fetched by SELECT * FROM people
Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6)
Person.where(["user_name = :u", { u: user_name }]).fourth
# File activerecord/lib/active_record/relation/finder_methods.rb, line 214 def fourth! find_nth! 3 end
То же самое, что и fourth, но вызывает ActiveRecord::RecordNotFound если запись не найдена.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 152
def last(limit = nil)
if limit
if order_values.empty? && primary_key
order(arel_table[primary_key].desc).limit(limit).reverse
else
to_a.last(limit)
end
else
find_last
end
end Находит последнюю запись (или последние N записей, если указан параметр). Если порядок не определен, он будет упорядочен по первичному ключу.
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
Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
Обратите внимание, что в последнем случае результаты отсортированы по возрастанию:
[#<Person id:2>, #<Person id:3>, #<Person id:4>]
а не:
[#<Person id:4>, #<Person id:3>, #<Person id:2>]
# File activerecord/lib/active_record/relation/finder_methods.rb, line 166
def last!
last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
end То же самое, что и last, но вызывает ActiveRecord::RecordNotFound если запись не найдена. Обратите внимание, что last! не принимает аргументов.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 176 def second find_nth(1, offset_index) end
Находит вторую запись. Если порядок не определен, он будет упорядочен по первичному ключу.
Person.second # returns the second object fetched by SELECT * FROM people
Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4)
Person.where(["user_name = :u", { u: user_name }]).second
# File activerecord/lib/active_record/relation/finder_methods.rb, line 182 def second! find_nth! 1 end
То же самое, что и second, но вызывает ActiveRecord::RecordNotFound если запись не найдена.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 104 def take(limit = nil) limit ? limit(limit).to_a : find_take end
Возвращает запись (или N записей, если указан параметр) без неявного порядка. Порядок будет зависеть от реализации базы данных. Если порядок указан, он будет соблюдаться.
Person.take # returns an object fetched by SELECT * FROM people LIMIT 1 Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5 Person.where(["name LIKE '%?'", name]).take
# File activerecord/lib/active_record/relation/finder_methods.rb, line 110
def take!
take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
end То же самое, что и take, но вызывает ActiveRecord::RecordNotFound если запись не найдена. Обратите внимание, что take! не принимает аргументов.
# File activerecord/lib/active_record/relation/finder_methods.rb, line 192 def third find_nth(2, offset_index) end
Находит третью запись. Если порядок не определен, он будет упорядочен по первичному ключу.
Person.third # returns the third object fetched by SELECT * FROM people
Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5)
Person.where(["user_name = :u", { u: user_name }]).third
# File activerecord/lib/active_record/relation/finder_methods.rb, line 198 def third! find_nth! 2 end
То же самое, что и third, но вызывает ActiveRecord::RecordNotFound, если запись не найдена.
Защищенные методы экземпляра
# File activerecord/lib/active_record/relation/finder_methods.rb, line 503
def find_last
if loaded?
@records.last
else
@last ||=
if limit_value
to_a.last
else
reverse_order.limit(1).to_a.first
end
end
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 479
def find_nth(index, offset)
if loaded?
@records[index]
else
offset += index
@offsets[offset] ||= find_nth_with_limit(offset, 1).first
end
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 488
def find_nth!(index)
find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 492
def find_nth_with_limit(offset, limit)
relation = if order_values.empty? && primary_key
order(arel_table[primary_key].asc)
else
self
end
relation = relation.offset(offset) unless offset.zero?
relation.limit(limit).to_a
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 432
def find_one(id)
if ActiveRecord::Base === id
id = id.id
ActiveSupport::Deprecation.warn(" You are passing an instance of ActiveRecord::Base to `find`.
Please pass the id of the object by calling `.id`
".squish)
end
relation = where(primary_key => id)
record = relation.take
raise_record_not_found_exception!(id, 0, 1) unless record
record
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 449
def find_some(ids)
result = where(primary_key => ids).to_a
expected_size =
if limit_value && ids.size > limit_value
limit_value
else
ids.size
end
# 11 ids with limit 3, offset 9 should give 2 results.
if offset_value && (ids.size - offset_value < expected_size)
expected_size = ids.size - offset_value
end
if result.size == expected_size
result
else
raise_record_not_found_exception!(ids, result.size, expected_size)
end
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 471
def find_take
if loaded?
@records.first
else
@take ||= limit(1).to_a.first
end
end # File activerecord/lib/active_record/relation/finder_methods.rb, line 411
def find_with_ids(*ids)
raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
expects_array = ids.first.kind_of?(Array)
return ids.first if expects_array && ids.first.empty?
ids = ids.flatten.compact.uniq
case ids.size
when 0
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
when 1
result = find_one(ids.first)
expects_array ? [ result ] : result
else
find_some(ids)
end
rescue RangeError
raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID"
end
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.