update_attributes(attributes) public

Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.

Show source
Register or log in to add new notes.
August 27, 2008
12 thanks

Only attr_accessible attributes will be updated

If your model specified attr_accessible attributes, only those attributes will be updated.

Use attr_accessible to prevent mass assignment (by users) of attributes that should not be editable by a user. Mass assignment is used in create and update methods of your standard controller.

For a normal user account, for example, you only want login and password to be editable by a user. It should not be possible to change the status attribute through mass assignment.

  class User < ActiveRecord::Base
    attr_accessible :login, :password
  end

So, doing the following will merrily return true, but will not update the status attribute.

  @user.update_attributes(:status => 'active')

If you want to update the status attribute, you should assign it separately.

  @user.status = 'active'
  save
August 14, 2008
4 thanks

Calls attribute setter for each key/value in the hash

This is a convenience to set multiple attributes at the same time. It calls the "setter" method

  self.attribute=(value)

for each key in the hash. If you have overridden the setter to add functionality, it will be called.

This also allows you to create non-table attributes that affect the record. For instance, a full_name=() method could parse the string and set the first_name=() and last_name() accordingly.

June 17, 2009
3 thanks

Skipping validation

Unlike the save method, you can’t pass false to update_attributes to tell it to skip validation. Should you wish to do this (consider carefully if this is wise) update the attributes explicitly then call save and pass false:

  @model_name.attributes = params[:model_name]
  @model_name.save false