Module: ActiveModelPersistence::PrimaryKey

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

Overview

Exposes the `primary_key` accessor to read or write the primary key attribute value

The primary key should be a unique (within its model class) identifier for a model.

By default, the `primary_key` accessors maps to the `id` attribute. You can change the attribute by setting the `primary_key` at the class level.

Examples:

By default, the primary key maps to the `id` attribute

class Employee
  include ActiveModelPersistence::PrimaryKey
  attribute :id, :integer
end
e1 = Employee.new(id: 1)
e1.primary_key #=> 1

Changing the primary key attribute

class Employee
  include ActiveModelPersistence::PrimaryKey
  attribute :short_id, :string
  # change the primary key
  self.primary_key = :short_id
end
e1 = Employee.new(short_id: 'couballj')
# `primary_key` can be used as an alias for `short_id`
e1.primary_key #=> 'couballj'
e1.primary_key = 'fthrock'
e1.short_id #=> 'fthrock'

Defined Under Namespace

Modules: ClassMethods