Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/fields.rb

Instance Method Summary (collapse)

Instance Method Details

- (Array<String>) attribute_names

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

Since:

  • 3.0.0



225
226
227
# File 'lib/mongoid/fields.rb', line 225

def attribute_names
  fields.keys
end

- (String) database_field_name(name)

Get the name of the provided field as it is stored in the database. Used in determining if the field is aliased or not.

Examples:

Get the database field name.

Model.database_field_name(:authorization)

Since:

  • 3.0.7



240
241
242
243
244
# File 'lib/mongoid/fields.rb', line 240

def database_field_name(name)
  return nil unless name
  normalized = name.to_s
  aliased_fields[normalized] || normalized
end

- (Field) field(name, options = {})

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

Options Hash (options):

  • :type (Class)

    The type of the field.

  • :label (String)

    The label for the field.

  • :default (Object, Proc)

    The field's default



261
262
263
264
265
266
267
268
269
# File 'lib/mongoid/fields.rb', line 261

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

- (Serializable) replace_field(name, type)

Replace a field with a new type.

Examples:

Replace the field.

Model.replace_field("_id", String)

Since:

  • 2.1.0



282
283
284
285
# File 'lib/mongoid/fields.rb', line 282

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

- (true, false) using_object_ids?

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

Examples:

Does this class use object ids?

person.using_object_ids?

Since:

  • 1.0.0



296
297
298
# File 'lib/mongoid/fields.rb', line 296

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