update_attributes で validation_context を指定するにはどうすればよいですか?
2 つの操作 (update_attributes なし) を使用してそれを行うことができます。
my_model.attributes = { :name => '123', :description => '345' }
my_model.save(:context => :some_context)
update_attributes で validation_context を指定するにはどうすればよいですか?
2 つの操作 (update_attributes なし) を使用してそれを行うことができます。
my_model.attributes = { :name => '123', :description => '345' }
my_model.save(:context => :some_context)
それを行う方法はありません。update_attributes
これが(のエイリアスであるupdate
)のコードです
def update(attributes)
with_transaction_returning_status do
assign_attributes(attributes)
save
end
end
ご覧のとおり、save
メソッドに引数を渡さずに、指定された属性を割り当てて保存するだけです。
with_transaction_returning_status
これらの操作は、一部の代入が関連付けのデータを変更する問題を防ぐために、渡されるブロックに含まれます。したがって、手動で呼び出したときに、これらの操作をより安全に囲むことができます。
簡単なトリックの 1 つは、次のようにコンテキスト依存のパブリック メソッドをモデルに追加することです。
def strict_update(attributes)
with_transaction_returning_status do
assign_attributes(attributes)
save(context: :strict)
end
end
(Rails 5 のすべてのモデルの基本クラス) にupdate_with_context
right を追加することで、これを改善できます。ApplicationRecord
したがって、コードは次のようになります。
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