If there is a way I can validate single attribute in Rails?
Something like:
ac_object.valid?(attribute_name)
I'm gonna use it for AJAX validation of particular model fields. Moving these validations to the Javascript makes code really ugly.
If there is a way I can validate single attribute in Rails?
Something like:
ac_object.valid?(attribute_name)
I'm gonna use it for AJAX validation of particular model fields. Moving these validations to the Javascript makes code really ugly.
Sometimes there are validations that are quite expensive (e.g. validations that need to perform database queries). In that case you need to avoid using
valid?
because it simply does a lot more than you need.There is an alternative solution. You can use the
validators_on
method ofActiveModel::Validations
.according to which you can manually validate for the attributes you want
e.g. we only want to validate the
title
ofPost
:Where
no_swearing
andspell_check_ok
are complex methods that are extremely expensive.We can do the following:
which will validate only the title attribute without invoking any other validations.
note
I am not completely confident that we are supposed to use
validators_on
safely so I would consider handling an exception in a sane way invalidates_title
.I wound up building on @xlembouras's answer and added this method to my
ApplicationRecord
:Then I can do stuff like this in a controller:
You can implement your own method in your model. Something like this
Or add it to
ActiveRecord::Base