Rails 3 - Pass a parameter to custom validation method

前端 未结 2 1788
旧巷少年郎
旧巷少年郎 2021-02-10 14:09

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

相关标签:
2条回答
  • 2021-02-10 14:26

    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!

    0 讨论(0)
  • 2021-02-10 14:28

    You could try

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

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

    0 讨论(0)
提交回复
热议问题