Validation_context & update_attributes

How can I specify validation_context with update_attributes?

I can do this using 2 operations (without update_attributes):

my_model.attributes = { :name => '123', :description => '345' } my_model.save(:context => :some_context) 
+4
source share
1 answer

There is no way to do this, here is the code for update_attributes (which is an alias for update )

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

As you can see, it simply assigns the given attributes and saves without passing any argument to the save method.

These operations are enclosed in a block passed to with_transaction_returning_status to prevent problems when some assignments modify data in associations. Thus, you are safer to enable these operations when called manually.

One simple trick is to add a context sensitive public method to your model as follows:

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

You can improve it by adding update_with_context directly to your ApplicationRecord (the base class for all models in Rails 5). So your code will look like this:

 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 
+5
source

Source: https://habr.com/ru/post/1384860/


All Articles