Custom validation

I wan’t to make my custom validation before saving an object.

  1. Why doesn’t this work?
    class User < ActiveRecord::Base

    def validate
    self.errors.add( ‘name’, ‘your name is always wrong!’ )
    end

    end
    (I get no error, but i still save the object)

  2. i) Why is this working?
    class User < ActiveRecord::Base

    validate do | record |
    record.errors.add( ‘name’, ‘your name is always wrong!’ )
    end

    end
    ii) What is ‘validate’? Is not a method of class ‘User’ because it’s not
    prefixed with ‘def’ (i.e. def validate … end)

  3. thanks

Mea culpa.
Version 1 works.

Still have 2. dilemma

George wrote:

I wan’t to make my custom validation before saving an object.

  1. Why doesn’t this work?
    class User < ActiveRecord::Base

    def validate
    self.errors.add( ‘name’, ‘your name is always wrong!’ )
    end

    end
    (I get no error, but i still save the object)

  2. i) Why is this working?
    class User < ActiveRecord::Base

    validate do | record |
    record.errors.add( ‘name’, ‘your name is always wrong!’ )
    end

    end
    ii) What is ‘validate’? Is not a method of class ‘User’ because it’s not
    prefixed with ‘def’ (i.e. def validate … end)

  3. thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs