method

assign_attributes

assign_attributes(new_attributes, options = {})
public

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

1Note

ActiveModel::MassAssignmentSecurity::Error

Ajedi32 ยท Sep 5, 20121 thank

Note that in the example shown in the documentation, user.assign_attributes({ :name => 'Josh', :is_admin => true }) would raise a ActiveModel::MassAssignmentSecurity::Error and would not actually update user.name, contrary to what the example seems to demonstrate.