Midwire

Ruby, Elixir, Macintosh and Other Technical Maunder.

Update ActiveRecord Instance With Validation Context

Validation contexts are really useful, however only the methods valid? and save allow you to pass a custom validation context. What about update?

If you want to pass a validation context when calling update on an Active Record model instance, add this to your base class, which is ApplicationRecord by default in Rails 4.x and 5.x.

1
2
3
4
5
6
7
8
9
10
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def update_with_context(new_attributes, context)
    with_transaction_returning_status do
      assign_attributes(new_attributes)
      save(context: context)
    end
  end
end

Now you can call mymodel.update_with_context(model_params, :my_special_context, and pass your custom validation context along.

Cheers!

Comments