Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to validate a specific attribute on an ActiveRecord without instantiating an object first?

For example, if I have a user model and I need to validate login only (which can happen when validating a form via ajax), it would be great if I use the same model validations defined in the User model without actually instantiating a User instance.

So in the controller I'd be able to write code like

User.valid_attribute?(:login, "login value")

Is there anyway I can do this?

like image 276
humanzz Avatar asked Jan 19 '09 10:01

humanzz


1 Answers

Since validations operate on instances (and they use the errors attribute of an instance as a container for error messages), you can't use them without having the object instantiated. Having said that, you can hide this needed behaviour into a class method:

class User < ActiveRecord::Base
  def self.valid_attribute?(attr, value)
    mock = self.new(attr => value)
    unless mock.valid?
      return mock.errors.has_key?(attr)
    end
    true
  end
end

Now, you can call

User.valid_attribute?(:login, "login value")

just as you intended.

(Ideally, you'd include that class method directly into the ActiveRecord::Base so it would be available to every model.)

like image 127
Milan Novota Avatar answered Nov 15 '22 21:11

Milan Novota