Reputation: 3183
This is a painfully noob question, but I have to ask it. I want validation to trip if a particular field, let's call it :token
isn't a particular string. So, I call my custom validation:
validate :use_beta_token
And then I define my validation method
def use_beta_token
errors.add(:token, "Incorrect beta token") if token not 'pizza'
end
Whenever I set the token to a string that isn't "pizza", and I test with valid?
it's coming back true
. What am I messing up here? I've also tried if token !== 'pizza'
, but that's not working either. I'm sure the answer is painfully obvious, but I can't seem to dig it up.
Upvotes: 0
Views: 115
Reputation: 1068
try
errors.add(:token, "Incorrect beta token") unless token == 'pizza'
the not method works like !, it's a unary boolean operator rather than a binary comparison operator.
as for how to write them, keep it concise. See the rails guide for examples.
Upvotes: 3
Reputation: 11628
One way to use custom validators for Rails 3 is to define your own Validator class that inherits from ActiveModel::Validator then implement the validate
method and attach errors like so:
# define my validator
class MyValidator < ActiveModel::Validator
# implement the method where the validation logic must reside
def validate(record)
# do my validations on the record and add errors if necessary
record.errors[:token] << "Incorrect beta token" unless token == 'pizza'
end
end
Once you define your validator, you must then include it into your model so it can be used and apply it with the validates_with
method.
class ModelName
# include my validator and validate the record
include ActiveModel::Validations
validates_with MyValidator
end
Upvotes: 0