Rails 3 - Pass a parameter to custom validation me

2020-06-04 13:54发布

问题:

I am looking to pass a value to a custom validation. I have done the following as a test:

validate :print_out, :parameter1 => 'Hello'

With this:

def print_out (input="blank")
  puts input
end

When creating an object or saving an object, the output is 'blank.' However, if called directly:

object.print_out "Test"

Test is instead outputted. The question is, why is my parameter not passing properly?

回答1:

Inside the 'config\initializers\' directory, you can create your own validations. As an example, let's create a validation 'validates_obj_length.' Not a very useful validation, but an acceptable example:

Create the file 'obj_length_validator.rb' within the 'config\intializers\' directory.

ActiveRecord::Base.class_eval do
    def self.validates_obj_length(*attr_names)
        options = attr_names.extract_options!
        validates_each(attr_names, options) do |record, attribute, value|
          record.errors[attribute] << "Error: Length must be " + options[:length].to_s unless value.length == options[:length]
        end
    end
end

Once you have this, you can use the very clean:

validates_obj_length :content, :length => 5

Basically, we reopen ActiveRecord::Base class and implement a new sub-validation. We use the splat (*) operator to accept an array of arguments. We then extract out the hash of options into our 'options' variable. Finally we implement our validation(s). This allows the validation to be used with any model anytime and stay DRY!



回答2:

You could try

validate do |object_name|
  object_name.print_out "Hello"
end

Instead of your validate :print_out, :parameter1 => 'Hello'.