Rails update_attributes without 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 => :adminenduser = User.newuser.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Erroruser.assign_attributes({ :name => 'Bob'})user.name # => "Bob"user.is_admin? # => falseuser.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 ofassign_attributes
update_attributes
= deprecated, alias ofupdate
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
You can use the 'attributes' method:
@car.attributes = {:model => 'Sierra', :years => '1990', :looks => 'Sexy'}
Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
attributes=(new_attributes, guard_protected_attributes = true)Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).
If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
class User < ActiveRecord::Base attr_protected :is_adminenduser = User.newuser.attributes = { :username => 'Phusion', :is_admin => true }user.username # => "Phusion"user.is_admin? # => falseuser.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)user.is_admin? # => true