123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Attributes::Readonly::ClassMethods

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Defined in: lib/mongoid/attributes/readonly.rb

Instance Method Summary

Instance Method Details

#attr_readonly(*names)

Note:

When a parent class contains readonly attributes and is then

Defines an attribute as readonly. This will ensure that the value for the attribute is only set when the document is new or we are creating. In other cases, the field write will be ignored with the exception of #remove_attribute and #update_attribute, where an error will get raised.

inherited by a child class, the child class will inherit the parent’s readonly attributes at the time of its creation. Updating the parent does not propagate down to child classes after wards.

Examples:

Flag fields as readonly.

class Band
  include Mongoid::Document
  field :name, type: String
  field :genre, type: String
  attr_readonly :name, :genre
end

Parameters:

  • *names (Symbol...)

    The names of the fields.

[ GitHub ]

  
# File 'lib/mongoid/attributes/readonly.rb', line 70

def attr_readonly(*names)
  self.readonly_attributes = self.readonly_attributes.dup
  names.each do |name|
    self.readonly_attributes << database_field_name(name)
  end
end