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.


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 4):

  • update_attributes = assign_attributes + save
  • attributes= = alias of assign_attributes
  • update = alias of update_attributes
  • 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_admin
    end
    
    user = User.new
    user.attributes = { :username => 'Phusion', :is_admin => true }
    user.username   # => "Phusion"
    user.is_admin?  # => false
    
    user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
    user.is_admin?  # => true
    
    链接地址: http://www.djcxy.com/p/66230.html

    上一篇: 如何将此ActiveRecord :: Observer转换为Service对象?

    下一篇: 属性没有保存?