Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing rails validation context outside of validations

I would like to use the rails validation contexts outside of the validations themselves, specifically in callbacks.

I can see in the source code of the valid? method that internally a validation_context attr_accessor is used but it seems to always be nil.

Looking at the rails source it seems that there is no way it will be anything but nil so perhaps it is a bug in rails?

https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations.rb#L331

like image 919
Paul Odeon Avatar asked Jan 01 '26 04:01

Paul Odeon


1 Answers

As @rowend points out, validation_context is (now) available in certain callbacks, including before_validation, but not most of the later ones. If you need the context later on, then it can be saved as an instance variable in an earlier callback.

One use for this is if you want to lock an associated object during the creation of a new object. As an example, a tree can only hold 100 apples, so you want to lock the tree every time you create an apple so that you don't accidentally add two apples simultaneously to a tree that already holds 99:

# app/models/apple.rb
before_validation :save_validation_context
around_create :lock_tree

def save_validation_context
  @saved_validation_context = validation_context
end

def lock_tree
  tree.with_lock do
    validate!(@saved_validation_context)
    yield
  end
end

This works with Rails version 6.1.7.2 and Ruby version 3.1.3.

like image 98
Dan Avatar answered Jan 04 '26 02:01

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!