2013-12-09 25 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)