method

update_attributes

rails latest stable - Class: ActiveRecord::Base

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

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.

5Notes

Only attr_accessible attributes will be updated

Ariejan · Aug 27, 200816 thanks

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

Calls attribute setter for each key/value in the hash

allen · Aug 14, 20084 thanks

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.

Skipping validation

andrewmcdonough · Jun 17, 20093 thanks

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

Skipping validation - follow up

bsbodden · Jul 20, 20121 thank

For Rails 2.x use #save(false) for Rails 3.x use #save(:validate => false)

The last existing version

codemuncher · Nov 16, 2012

It says: The last existing version, and yet when I run a rails console in a 3.0.17 and try the method, it just works. Or does it mean it was never worked on past 2.3.8 ?