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.
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.
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.
create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With