instance method assign_attributes

Ruby on Rails 3.1.12

Since v2.3.18 Last seen in v3.1.12

Available in: v2.3.18 v3.1.12

Signature

assign_attributes(new_attributes, options = {})

Allows you to set all the attributes for a particular mass-assignment security role by passing in a hash of attributes with keys matching the attribute names (which again matches the column names) and the role name using the :as option.

To bypass mass-assignment security you can use the :without_protection => true option.

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true })
user.name       # => "Josh"
user.is_admin?  # => false

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
user.name       # => "Josh"
user.is_admin?  # => true

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
user.name       # => "Josh"
user.is_admin?  # => true

Parameters

new_attributes req
options opt = {}
Source
# File activerecord/lib/active_record/base.rb, line 1747
      def assign_attributes(new_attributes, options = {})
        return unless new_attributes

        attributes = new_attributes.stringify_keys
        multi_parameter_attributes = []
        @mass_assignment_options = options

        unless options[:without_protection]
          attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role)
        end

        attributes.each do |k, v|
          if k.include?("(")
            multi_parameter_attributes << [ k, v ]
          elsif respond_to?("#{k}=")
            send("#{k}=", v)
          else
            raise(UnknownAttributeError, "unknown attribute: #{k}")
          end
        end

        @mass_assignment_options = nil
        assign_multiparameter_attributes(multi_parameter_attributes)
      end

Defined in activerecord/lib/active_record/base.rb line 1747 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Base

Type at least 2 characters to search.

↑↓ navigate · open · esc close