16

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?

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

2

You can just do something like this:

def validate
  errors.add('That particular field', 'can not be the value you presented') if !self.field_to_check.blank? && self.field_to_check == 'I AM COOL'
end

No need to call reference it, as I believe the validate method is processed (if it exists) after any validates_uniqueness_of -like validations.

Added: More information in the Rails API docs here.

Comments

0

You should also be able to use a Ruby lambda to help with method based validation of your model attributes (x, y) like below:

validate -> { my_custom_validation(parameter1: x, parameter2: y) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.