Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a custom validation method with parameters for my ActiveRecord model?

In my model I have:

validate :my_custom_validation

def my_custom_validation
 errors.add_to_base("error message") if condition.exists?
end

I would like to add some parameters to mycustomer vaildation like so:

validate :my_custom_validation, :parameter1 => x, :parameter2 => y

How do I write the mycustomvalidation function to account for parameters?

like image 239
go minimal Avatar asked Sep 19 '08 22:09

go minimal


People also ask

What methods should you implement for your custom validator?

Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.


1 Answers

Validators usualy have an array parameter indicating, first, the fields to validate and lastly (if it exists) a hash with the options. In your example:

:my_custom_validation, parameter1: x, parameter2: y

:my_custom_validation would be a field name, while parameter1: x, parameter2: y would be a hash:

{ parameter1: x, parameter2: y}

Therefore, you'd do something like:

def my_custom_validation(*attr)
    options = attr.pop if attr.last.is_a? Hash
    # do something with options
    errors.add_to_base("error message") if condition.exists?

end
like image 101
paradoja Avatar answered Sep 27 '22 15:09

paradoja