有沒有辦法做到這一點,下面是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