1
votes

I am trying to learn custom validation. Below is the simple code:

class User < ActiveRecord::Base
  validates :username, presence: true,length: { in: 6..20 }
  validate :name_cannot_be_tushar

  def name_cannot_be_tushar
    if username == "Tushar"
        errors.add(:username, "can't be Tushar")
    end
  end
end

When I am trying to insert data through rails console,

2.3.0 :014 > User.create(username:"Tushar",password:"ABC") (0.1ms) begin transaction SQL (0.4ms) INSERT INTO "users" ("username", "password", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["username", "Tushar"], ["password", "ABC"], ["created_at", "2016-04-14 09:23:14.077264"], ["updated_at", "2016-04-14 09:23:14.077264"]] (12.9ms) commit transaction => # 2.3.0 :015 >

It is letting me insert the data. What do I change to make my custom validation method work?

1
Which version of Rails you are using?Arslan Ali

1 Answers

3
votes

Your code is absolutely fine. You may need to restart rails console, and it will work fine. Rails console session doesn't automatically load recent changes in your model.