Skip to content

Instantly share code, notes, and snippets.

@sandheepg
Created March 10, 2017 13:05
Show Gist options
  • Select an option

  • Save sandheepg/8a339d7e613eadc9afb0bd38c515fe2d to your computer and use it in GitHub Desktop.

Select an option

Save sandheepg/8a339d7e613eadc9afb0bd38c515fe2d to your computer and use it in GitHub Desktop.
Validate single model attribute in rails

Checking a single attribute on a model for validity doesn’t seem to be possible in Rails. Or at least i couldn’t find a quick answer googling around or looking through the ActiveRecord code.

What I really want to do is pass a hash into valid? with the attributes i want to validate or have an attribute_valid? method. This level of granularity is often useful in AJAX heavy apps. For instance, checking for username availability and validity as the user types during username selection.

Here is a quick solution for one User model.

def attribute_valid?(attr, value)
u = User.new(attr => value))
u.valid?
!u.errors.has_key?(:attr)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment