Different between update, update_columns, update_column, update_attributes, assign_attributes

update(id, attributes) public

Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

Parameters

  • id – This should be the id or an array of ids to be updated.
  • attributes – This should be a hash of attributes to be set on the object, or an array of hashes.
     # Updating one record:
      Person.update(15, :user_name => 'Samuel', :group => 'expert')
    
      # Updating multiple records:
      people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
      Person.update(people.keys, people.values)

update_columns(attributes) public

Updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver:

user.update_columns(last_request_at: Time.current)

This is the fastest way to update attributes because it goes straight to the database, but take into account that in consequence the regular update procedures are totally bypassed. In particular:

This method raises an +ActiveRecord::ActiveRecordError+ when called on new objects, or when at least one of the attributes is marked as readonly


update_column(name, value) public

Equivalent to update_columns(name => value).


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.


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 ofattributes 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

Source: http://apidock.com/rails/ActiveRecord

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s