Update ActiveRecord Instance With Validation Context

Published: Feb 6, 2018 by Midwire

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 versions starting with 4.x.

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

Share

Latest Posts

Mask Your IP Address For Fun And Profit

Why would anyone want to mask or change their IP address? There are many possible reasons, but here are a few:

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?

Why Not Google Chrome?

Why you should not use the Google Chrome browser