Module: ActiveAttr::MassAssignment

Extended by:
ActiveSupport::Concern
Includes:
ChainableInitialization
Included in:
Model, Serialization
Defined in:
lib/active_attr/mass_assignment.rb

Overview

MassAssignment allows you to bulk set and update attributes

Including MassAssignment into your model gives it a set of mass assignment methods, similar to those found in ActiveRecord.

Examples:

Usage

class Person
  include ActiveAttr::MassAssignment
end

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#assign_attributes(new_attributes, options = {}) ⇒ Object

Mass update a model’s attributes

Examples:

Assigning a hash

person.assign_attributes(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each)

    Attributes used to populate the model

  • options (Hash, #[]) (defaults to: {})

    Options that affect mass assignment

Options Hash (options):

  • :as (Symbol) — default: :default

    Mass assignment role

  • :without_protection (true, false) — default: false

    Bypass mass assignment security if true

Since:

  • 0.1.0



36
37
38
39
40
41
42
43
# File 'lib/active_attr/mass_assignment.rb', line 36

def assign_attributes(new_attributes, options={})
  sanitized_new_attributes = sanitize_for_mass_assignment_if_sanitizer new_attributes, options

  sanitized_new_attributes.each do |name, value|
    writer = "#{name}="
    send writer, value if respond_to? writer
  end if sanitized_new_attributes
end

#attributes=(new_attributes) ⇒ Object

Mass update a model’s attributes

Examples:

Assigning a hash

person.attributes = { :first_name => "Chris", :last_name => "Griego" }
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each)

    Attributes used to populate the model

  • options (Hash, #[])

    Options that affect mass assignment

Since:

  • 0.1.0



55
56
57
# File 'lib/active_attr/mass_assignment.rb', line 55

def attributes=(new_attributes)
  assign_attributes new_attributes
end

#initialize(attributes = nil, options = {}) ⇒ Object

Initialize a model with a set of attributes

Examples:

Initializing with a hash

person = Person.new(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each)

    Attributes used to populate the model

  • options (Hash, #[]) (defaults to: {})

    Options that affect mass assignment

Since:

  • 0.1.0



69
70
71
72
# File 'lib/active_attr/mass_assignment.rb', line 69

def initialize(attributes=nil, options={})
  assign_attributes attributes, options
  super
end