Rails的update_attributes的不救?Rails、update_attributes

2023-09-08 15:48:15 作者:单杀

时有替代update_attributes的不保存记录?

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

顺便说一句,我知道我能 @ car.model ='塞拉利昂',但我想更新他们都在同一行。

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

推荐答案

我相信你正在寻找的是assign_attributes.

I believe what you are looking for is assign_attributes.

这是基本相同update_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