Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails update_attributes without save?

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.

like image 712
tybro0103 Avatar asked Jul 21 '11 01:07

tybro0103


People also ask

Does Update_attributes call save?

Use update_attribute to skip validations. update_attribute uses save(false) while update_attributes uses save (which means save(true)). If perform_validation is false while calling save then it skips validation, and it also means that all the before_* callbacks associated with save.

Does assign_ attributes save?

Starting in Rails 3.1, assign_attributes is an instance method that will update the attributes of a given object without actually saving to the database.

Does Rails create save?

create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!


2 Answers

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 < 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 
like image 57
Ajedi32 Avatar answered Oct 13 '22 20:10

Ajedi32


You can use assign_attributes or attributes= (they're the same)

Update methods cheat sheet (for Rails 6):

  • update = assign_attributes + save
  • attributes= = alias of assign_attributes
  • update_attributes = deprecated, alias of update

Source:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_assignment.rb

Another cheat sheet:
http://www.davidverhasselt.com/set-attributes-in-activerecord/#cheat-sheet

like image 28
Yarin Avatar answered Oct 13 '22 21:10

Yarin