Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/fields.rb

Instance Method Summary collapse

Instance Method Details

#attribute_namesArray<String>

Returns an array of names for the attributes available on this object.

Provides the field names in an ORM-agnostic way. Rails v3.1+ uses this method to automatically wrap params in JSON requests.

Examples:

Get the field names

Model.attribute_names

Returns:

  • (Array<String>)

    The field names

Since:

  • 3.0.0



174
175
176
# File 'lib/mongoid/fields.rb', line 174

def attribute_names
  fields.keys
end

#field(name, options = {}) ⇒ Field

Defines all the fields that are accessible on the Document For each field that is defined, a getter and setter will be added as an instance method to the Document.

Examples:

Define a field.

field :score, :type => Integer, :default => 0

Parameters:

  • name (Symbol)

    The name of the field.

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

    The options to pass to the field.

Options Hash (options):

  • :type (Class)

    The type of the field.

  • :label (String)

    The label for the field.

  • :default (Object, Proc)

    The field’s default

Returns:

  • (Field)

    The generated field



193
194
195
196
197
198
199
200
201
# File 'lib/mongoid/fields.rb', line 193

def field(name, options = {})
  named = name.to_s
  Validators::Macro.validate(self, name, options)
  added = add_field(named, options)
  descendants.each do |subclass|
    subclass.add_field(named, options)
  end
  added
end

#replace_field(name, type) ⇒ Serializable

Replace a field with a new type.

Examples:

Replace the field.

Model.replace_field("_id", String)

Parameters:

  • name (String)

    The name of the field.

  • type (Class)

    The new type of field.

Returns:

  • (Serializable)

    The new field.

Since:

  • 2.1.0



214
215
216
217
# File 'lib/mongoid/fields.rb', line 214

def replace_field(name, type)
  remove_defaults(name)
  add_field(name, fields[name].options.merge(type: type))
end

#using_object_ids?true, false

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

Examples:

Does this class use object ids?

person.using_object_ids?

Returns:

  • (true, false)

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

Since:

  • 1.0.0



228
229
230
# File 'lib/mongoid/fields.rb', line 228

def using_object_ids?
  fields["_id"].object_id_field?
end