Search code examples
ruby-on-rails-3activemodel

Active Model Validations rails 3


I have a message model and i have been looking at various gems/js for client side validation. I then started reading about Active Model Validations, im pretty new to rails so please forgive me for not totally understanding the documentation.

Firstly am i correct in saying that i can perform client side validation with ActiveModel Validation and set my own custom error messages

I have at the top of my message model

include ActiveModel::Validations

Further reading has identified

i should be using

 validates_with MyValidator

But this does not work as i get error message

uninitialized constant Message::MyValidator

if i place this in the model

I have also read that-

 To cause a validation error, you must add to the record‘s errors directly from within the validators message

class MyValidator < ActiveModel::Validator
def validate(record)
record.errors.add :base, "This is some custom error message"
record.errors.add :first_name, "This is some complex validation"
# etc...
end

So this is saying i can add my own custom error messages client side?

My issue at the moment is getting my head around what it is stating to do, where do i put these classes and methods etc.. If anyone can point me in the right direction i would be grateful, i really want to learn

Thanks


Solution

  • ActiveModel validations do not provide client side validation. If you'd like to use your Rails validators on the client side, I'd suggest the client_side_validations gem.

    If you're having trouble getting started, I'd suggest performing a single, simple validation in your model and verifying that it works before trying to move it client-side. For example, in your Message class:

    # app/models/message.rb
    class Message
      include ActiveModel::Validations
      attr_accessor :sender
      validates :sender, presence: true
    end
    
    # in the console
    m = Message.new
    
    m.valid?                #=> false
    m.errors.full_messages  #=> ["Sender can't be blank"]
    

    Then start working with other types of validates, like length or format, then custom validations with the validate method, and then if you finally feel like you need it, a full validation class using validates_with.