Module: ActiveModelPersistence::Indexable

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::Attributes, ActiveModel::Model, PrimaryKey
Included in:
Persistence, PrimaryKeyIndex
Defined in:
lib/active_model_persistence/indexable.rb

Overview

Include in your model to enable index support

Define an index in the model's class using the `index` method. This will create a `find_by_*` method for each index to find the objects by their keys.

Each index has a name which must be unique for the model. The name is used to create the `find_by_*` method. eg. for the 'id' index, the `find_by_id` method will be created.

Unique indexes are defined by passing `unique: true` to the `index` method. A unique index defines a `find_by_*` method that will return a single object or nil if no object is found for the key.

A non-unique index will define a `find_by_*` method that will return an array of objects which may be empty.

Examples:

class Employee
  include ActiveModelPersistence::Indexable

  # Define ActiveModel attributes
  attribute :id, :integer
  attribute :name, :string
  attribute :manager_id, :integer
  attribute :birth_date, :date

  # Define indexes
  index :id, unique: true
  index :manager_id, key_value_source: :manager_id
  index :birth_year, key_value_source: ->(o) { o.birth_date.year }
end

e1 = Employee.new(id: 1, name: 'James', manager_id: 3, birth_date: Date.new(1967, 3, 15))
e2 = Employee.new(id: 2, name: 'Frank', manager_id: 3, birth_date: Date.new(1968, 1, 27))
e3 = Employee.new(id: 3, name: 'Aaron', birth_date: Date.new(1968, 6, 16))

# This should be done by Employee.create or Employee#save from ActiveModelPersistence::Persistence
[e1, e2, e3].each { |e| e.update_indexes }

# Use the find_by_* methods to find objects
#
Employee.find_by_id(1).name # => 'James'
Employee.find_by_manager_id(3).map(&:name) # => ['James', 'Frank']
Employee.find_by_birth_year(1967).map(&:name) # => ['James']
Employee.find_by_birth_year(1968).map(&:name) # => ['Frank', 'Aaron']

Defined Under Namespace

Modules: ClassMethods