123456789_123456789_123456789_123456789_123456789_

Module: ActiveRecord::AttributeAssignment

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Defined in: activerecord/lib/active_record/attribute_assignment.rb

Class Method Summary

Instance Attribute Summary

Instance Method Summary

  • #assign_attributes(new_attributes) (also: #attributes=)

    Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names (which again matches the column names).

Instance Attribute Details

#attributes=(new_attributes) (writeonly)

Alias for #assign_attributes.

[ GitHub ]

  
# File 'activerecord/lib/active_record/attribute_assignment.rb', line 49

alias attributes= assign_attributes

Instance Method Details

#assign_attributes(new_attributes) Also known as: #attributes=

Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names (which again matches the column names).

If the passed hash responds to permitted? method and the return value of this method is false an ::ActiveModel::ForbiddenAttributesError exception is raised.

cat = Cat.new(name: "Gorby", status: "yawning")
cat.attributes # =>  { "name" => "Gorby", "status" => "yawning", "created_at" => nil, "updated_at" => nil}
cat.assign_attributes(status: "sleeping")
cat.attributes # =>  { "name" => "Gorby", "status" => "sleeping", "created_at" => nil, "updated_at" => nil }

New attributes will be persisted in the database when the object is saved.

Aliased to #attributes=.

[ GitHub ]

  
# File 'activerecord/lib/active_record/attribute_assignment.rb', line 23

def assign_attributes(new_attributes)
  if !new_attributes.respond_to?(:stringify_keys)
    raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
  end
  return if new_attributes.blank?

  attributes                  = new_attributes.stringify_keys
  multi_parameter_attributes  = []
  nested_parameter_attributes = []

  attributes = sanitize_for_mass_assignment(attributes)

  attributes.each do |k, v|
    if k.include?("(")
      multi_parameter_attributes << [ k, v ]
    elsif v.is_a?(Hash)
      nested_parameter_attributes << [ k, v ]
    else
      _assign_attribute(k, v)
    end
  end

  assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
  assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
end