HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsCritical

Rails update_attributes without save?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withoutsaverailsupdate_attributes

Problem

Is there an alternative to update_attributes that does not save the record?

So I could do something like:

@car = Car.new(:make => 'GMC')
#other processing
@car.update_attributes(:model => 'Sierra', :year => "2012", :looks => "Super Sexy, wanna make love to it")
#other processing
@car.save


BTW, I know I can @car.model = 'Sierra', but I want to update them all on one line.

Solution

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User  :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Code Snippets

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 }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Context

Stack Overflow Q#6770350, score: 657

Revisions (0)

No revisions yet.