2013-12-09 26 views

回答

1

按照Rails docs

更新(属性)

从更新传入的散列并保存记录,所有包裹在一个交易模型的属性。如果该对象无效,则保存将失败并返回false。

所以尽量

model.update(dat_hash) #dat_hash being the hash with the attributes

我一直在做对Rails 3.2同样的事情用update_attributes方法,这是同样的事情。这是我的代码:

def update 
    @form = get_form(params[:id]) 
    @form.update_attributes(params[:form]) 
    @form.save 
    if @form.save 
    render json: @form 
    else 
    render json: @form.errors.full_messages, status: :unprocessable_entity 
    end 
end 

它只更新散列中的属性。

2

超级简单!

更新的属性不保存:

model.attributes = your_hash 
# in spite of resembling an assignemnt, it just sets the given attributes 

更新属性节省:

model.update_attributes(your_hash) 
# if it fails because of validation, the attributes are update in your object 
# but not in the database 

更新属性,保存,如果无法保存提高

model.update_attributes!(your_hash)