method

attributes=

attributes=(new_attributes, guard_protected_attributes = true)
public

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

If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.

  class User < ActiveRecord::Base
    attr_protected :is_admin
  end

  user = User.new
  user.attributes = { :username => 'Phusion', :is_admin => true }
  user.username   # => "Phusion"
  user.is_admin?  # => false

  user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
  user.is_admin?  # => true

2Notes

Update attributes on mulitple models

patrickberkeley · Oct 1, 2009

Updates attributes on multiple models, saves each if validations pass.

def update_multiple
@items = Item.find(params[:item_ids])
@items.each do |item|
  item.attributes = params[:item].reject { |k,v| v.blank? }
end
if @items.all?(&:valid?)
  @items.each(&:save!)
  flash[:notice] = "Updated items!"
  redirect_to items_path
else
  flash[:notice] = "Please enter valid data."
  render :action => 'edit_multiple'
end
end

the source is wrong!

abstraktor · Apr 6, 2011

in 3.0.5, the source code in line 15 looks like this: respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")

whats wrong with apidock?