2011-12-06 22 views
4

如何使用update_attributes指定validation_context?validation_context&update_attributes

我能做到這一點使用2個操作(不update_attributes方法):

my_model.attributes = { :name => '123', :description => '345' } 
my_model.save(:context => :some_context) 

回答

5

有沒有辦法做到這一點,下面是update_attributes的代碼(這是update的別名)

def update(attributes) 
    with_transaction_returning_status do 
    assign_attributes(attributes) 
    save 
    end 
end 

正如你可以看到它只是分配給定的屬性並保存而不傳遞任何參數到save方法。

這些操作被包含在傳遞給with_transaction_returning_status的塊中,以防止某些分配修改關聯中的數據時出現問題。所以當你手動調用時你更安全地包含這些操作。

一個簡單的竅門是上下文相關的公共方法添加到您的模型是這樣的:

def strict_update(attributes) 
    with_transaction_returning_status do 
    assign_attributes(attributes) 
    save(context: :strict) 
    end 
end 

您可以通過添加update_with_context到您ApplicationRecord改進(基類中的Rails的所有型號5)。所以你的代碼看起來像這樣:

class ApplicationRecord < ActiveRecord::Base 
    self.abstract_class = true 

    # Update attributes with validation context. 
    # In Rails you can provide a context while you save, for example: `.save(:step1)`, but no way to 
    # provide a context while you update. This method just adds the way to update with validation 
    # context. 
    # 
    # @param [Hash] attributes to assign 
    # @param [Symbol] validation context 
    def update_with_context(attributes, context) 
    with_transaction_returning_status do 
     assign_attributes(attributes) 
     save(context: context) 
    end 
    end 
end