Spec-Zone.ru › Ruby on Rails 8.1

модуль ActiveRecord::FinderMethods

Константы

ONE_AS_ONE

Открытые методы экземпляра

exists? (conditions = :none) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 357
    def exists?(conditions = :none)
      return false if @none

      if Base === conditions
        raise ArgumentError, <<-MSG.squish
          You are passing an instance of ActiveRecord::Base to `exists?`.
          Please pass the id of the object by calling `.id`.
        MSG
      end

      return false if !conditions || limit_value == 0

      if eager_loading?
        relation = apply_join_dependency(eager_loading: false)
        return relation.exists?(conditions)
      end

      relation = construct_relation_for_exists(conditions)
      return false if relation.where_clause.contradiction?

      skip_query_cache_if_necessary do
        with_connection do |c|
          c.select_rows(relation.arel, "#{model.name} Exists?").size == 1
        end
      end
    end

Возвращает true, если в таблице существует запись, соответствующая id или заданным условиям, и false в противном случае. Аргумент может принимать шесть форм:

  • Integer — находит запись с этим первичным ключом.

  • String — находит запись с первичным ключом, соответствующим этой строке (например, '5').

  • Array — находит запись, соответствующую условиям в стиле where (например, ['name LIKE ?', "%#{query}%"]).

  • Hash — находит запись, соответствующую условиям в стиле where (например, {name: 'David'}).

  • false — всегда возвращает false.

  • Без аргументов — возвращает false, если отношение пусто, и true в противном случае.

Подробнее о том, как задавать условия в виде хеша или массива, см. раздел Conditions во введении к 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?
Person.where(name: 'Spartacus', rating: 4).exists?
fifth () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 271
def fifth
  find_nth 4
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
fifth! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 277
def fifth!
  fifth || raise_record_not_found_exception!
end

То же, что и fifth, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

find (*args) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 98
def find(*args)
  return super if block_given?
  find_with_ids(*args)
end

Поиск по идентификатору — это может быть конкретный идентификатор (ID), список идентификаторов (ID, ID, ID) или массив идентификаторов ([ID, ID, ID]). `ID` означает «идентификатор». Для моделей с первичным ключом из одного столбца `ID` будет одним значением, а для моделей с составным первичным ключом — массивом значений. Если одну или несколько записей по запрошенным идентификаторам найти не удастся, будет вызвано исключение ActiveRecord::RecordNotFound. Если первичный ключ имеет целочисленный тип, find преобразует аргументы с помощью 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), or with composite primary key [7, 17]
Person.find([1])        # returns an array for the object with ID = 1
Person.where("administrator = 1").order("created_on DESC").find(1)

Поиск записи в модели с составным первичным ключом

TravelRoute.primary_key = [:origin, :destination]

TravelRoute.find(["Ottawa", "London"])
# => #<TravelRoute origin: "Ottawa", destination: "London">

TravelRoute.find([["Paris", "Montreal"]])
# => [#<TravelRoute origin: "Paris", destination: "Montreal">]

TravelRoute.find(["New York", "Las Vegas"], ["New York", "Portland"])
# => [
#      #<TravelRoute origin: "New York", destination: "Las Vegas">,
#      #<TravelRoute origin: "New York", destination: "Portland">
#    ]

TravelRoute.find([["Berlin", "London"], ["Barcelona", "Lisbon"]])
# => [
#      #<TravelRoute origin: "Berlin", destination: "London">,
#      #<TravelRoute origin: "Barcelona", destination: "Lisbon">
#    ]

ПРИМЕЧАНИЕ: возвращаемые записи располагаются в том же порядке, что и переданные вами идентификаторы. Если нужно отсортировать результаты по данным базы данных, можно использовать метод ActiveRecord::QueryMethods#where и явно задать параметр ActiveRecord::QueryMethods#order. Однако метод ActiveRecord::QueryMethods#where не вызывает исключение ActiveRecord::RecordNotFound.

Поиск с блокировкой

Пример поиска с блокировкой: представьте две параллельные транзакции, каждая из которых прочитает 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.find_or_initialize_by(name: 'Spartacus', rating: 4)
# returns the first item or returns a new instance (requires you call .save to persist against the database).

Person.find_or_create_by(name: 'Spartacus', rating: 4)
# returns the first item or creates it and returns it.

Альтернативы методу 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.

Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
# returns an Array of the required fields.

Особые случаи

Person.find(37)          # raises ActiveRecord::RecordNotFound exception if the record with the given ID does not exist.
Person.find([37])        # raises ActiveRecord::RecordNotFound exception if the record with the given ID in the input array does not exist.
Person.find(nil)         # raises ActiveRecord::RecordNotFound exception if the argument is nil.
Person.find([])          # returns an empty array if the argument is an empty array.
Person.find              # raises ActiveRecord::RecordNotFound exception if the argument is not provided.
Вызывает метод родительского класса
find_by (arg, *args) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 111
def find_by(arg, *args)
  where(arg, *args).take
end

Находит первую запись, соответствующую заданным условиям. Порядок не задается автоматически, поэтому, если он имеет значение, укажите его самостоятельно.

Если запись не найдена, возвращает nil.

Post.find_by name: 'Spartacus', rating: 4
Post.find_by "published_at < ?", 2.weeks.ago
find_by! (arg, *args) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 117
def find_by!(arg, *args)
  where(arg, *args).take!
end

Работает как find_by, но, если запись не найдена, вызывает исключение ActiveRecord::RecordNotFound.

find_sole_by (arg, *args) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 160
def find_sole_by(arg, *args)
  where(arg, *args).sole
end

Находит единственную соответствующую запись. Если запись не найдена, вызывает исключение ActiveRecord::RecordNotFound. Если найдено несколько записей, вызывает исключение ActiveRecord::SoleRecordExceeded.

Product.find_sole_by(["price = %?", price])
first (limit = nil) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 173
def first(limit = nil)
  if limit
    find_nth_with_limit(0, limit)
  else
    find_nth 0
  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
first! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 183
def first!
  first || raise_record_not_found_exception!
end

То же, что и first, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена. Обратите внимание, что first! не принимает аргументов.

forty_two () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 287
def forty_two
  find_nth 41
end

Находит сорок вторую запись. Также известно как обращение к «реддиту». Если порядок не задан, записи упорядочиваются по первичному ключу.

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
forty_two! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 293
def forty_two!
  forty_two || raise_record_not_found_exception!
end

То же, что и forty_two, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

fourth () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 255
def fourth
  find_nth 3
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
fourth! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 261
def fourth!
  fourth || raise_record_not_found_exception!
end

То же, что и fourth, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

include? (record) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 389
def include?(record)
  # The existing implementation relies on receiving an Active Record instance as the input parameter named record.
  # Any non-Active Record object passed to this implementation is guaranteed to return `false`.
  return false unless record.is_a?(model)

  if loaded? || offset_value || limit_value || having_clause.any?
    records.include?(record)
  else
    id = if record.class.composite_primary_key?
      record.class.primary_key.zip(record.id).to_h
    else
      record.id
    end

    exists?(id)
  end
end

Возвращает true, если отношение содержит указанную запись, и false в противном случае.

Если отношение загружено, запрос не выполняется: указанная запись сравнивается с записями в памяти. Если отношение не загружено, выполняется эффективный запрос на проверку существования, как в exists?.

Также имеет псевдоним: member?
last (limit = nil) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 202
def last(limit = nil)
  return find_last(limit) if loaded? || has_limit_or_offset?

  result = ordered_relation.limit(limit)
  result = result.reverse_order!

  limit ? result.reverse : result.first
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>]
last! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 213
def last!
  last || raise_record_not_found_exception!
end

То же, что и last, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена. Обратите внимание, что last! не принимает аргументов.

member? (record)
Псевдоним для: include?
second () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 223
def second
  find_nth 1
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
second! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 229
def second!
  second || raise_record_not_found_exception!
end

То же, что и second, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

second_to_last () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 319
def second_to_last
  find_nth_from_last 2
end

Находит предпоследнюю запись. Если порядок не задан, записи упорядочиваются по первичному ключу.

Person.second_to_last # returns the second-to-last object fetched by SELECT * FROM people
Person.offset(3).second_to_last # returns the second-to-last object from OFFSET 3
Person.where(["user_name = :u", { u: user_name }]).second_to_last
second_to_last! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 325
def second_to_last!
  second_to_last || raise_record_not_found_exception!
end

То же, что и second_to_last, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

sole () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 143
def sole
  found, undesired = take(2)

  if found.nil?
    raise_record_not_found_exception!
  elsif undesired.nil?
    found
  else
    raise ActiveRecord::SoleRecordExceeded.new(self)
  end
end

Находит единственную соответствующую запись. Если запись не найдена, вызывает исключение ActiveRecord::RecordNotFound. Если найдено несколько записей, вызывает исключение ActiveRecord::SoleRecordExceeded.

Product.where(["price = %?", price]).sole
take (limit = nil) Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 128
def take(limit = nil)
  limit ? find_take_with_limit(limit) : 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
take! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 134
def take!
  take || raise_record_not_found_exception!
end

То же, что и take, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена. Обратите внимание, что take! не принимает аргументов.

third () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 239
def third
  find_nth 2
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
third! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 245
def third!
  third || raise_record_not_found_exception!
end

То же, что и third, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

third_to_last () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 303
def third_to_last
  find_nth_from_last 3
end

Находит третью с конца запись. Если порядок не задан, записи упорядочиваются по первичному ключу.

Person.third_to_last # returns the third-to-last object fetched by SELECT * FROM people
Person.offset(3).third_to_last # returns the third-to-last object from OFFSET 3
Person.where(["user_name = :u", { u: user_name }]).third_to_last
third_to_last! () Показать исходный код
# File activerecord/lib/active_record/relation/finder_methods.rb, line 309
def third_to_last!
  third_to_last || raise_record_not_found_exception!
end

То же, что и third_to_last, но вызывает исключение ActiveRecord::RecordNotFound, если запись не найдена.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API