Module: Mongoid::Keys::ClassMethods

Defined in:
lib/mongoid/keys.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#identity(options = {}) ⇒ Object

Used for telling Mongoid on a per model basis whether to override the default BSON::ObjectId and use a different type. This will be expanded in the future for requiring a PkFactory if the type is not a BSON::ObjectId or String.

Examples:

Change the documents key type.

class Person
  include Mongoid::Document
  identity :type => String
end

Parameters:

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :type (Class)

    The type of the id.

Since:

  • 2.0.0.beta.1



103
104
105
106
107
# File 'lib/mongoid/keys.rb', line 103

def identity(options = {})
  type = options[:type]
  replace_field("_id", type)
  self.using_object_ids = (type == BSON::ObjectId)
end

#key(*fields) ⇒ Object

Defines the field that will be used for the id of this Document. This set the id of this Document before save to a parameterized version of the field that was supplied. This is good for use for readable URLS in web applications.

Examples:

Create a composite id.

class Person
  include Mongoid::Document
  key :first_name, :last_name
end

Parameters:

  • The (Array<Symbol>)

    fields the key is composed of.

Since:

  • 1.0.0



123
124
125
126
127
128
# File 'lib/mongoid/keys.rb', line 123

def key(*fields)
  self.primary_key = fields
  self.key_formatter = block_given? ? Proc.new : nil
  identity(:type => String)
  set_callback(:save, :around, :set_composite_key)
end

#using_object_ids?true, false

Convenience method for determining if we are using BSON::ObjectIds as our id.

Examples:

Does this class use object ids?

person.using_object_ids?

Returns:

  • (true, false)

    If the class uses BSON::ObjectIds for the id.

Since:

  • 1.0.0



139
140
141
# File 'lib/mongoid/keys.rb', line 139

def using_object_ids?
  using_object_ids
end