Method: Mongoid::Keys::ClassMethods#key

Defined in:
lib/mongoid/keys.rb

#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

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