0

loading a form with a custom validator is generating a NoMethodError

undefined method `validates_soggetti'

set-up

gem 'rails', '3.2.13'
gem 'client_side_validations', :github => 'bcardarella/client_side_validations', :branch => '3-2-stable'

Initializer has block for attached message uncommented.
app/validators/soggetti_validator.rb contains

class SoggettiValidator < ActiveModel::EachValidator

  def validate(record)
    unless :quantita >= :soggetti
      record.errors.add(:soggetti, :too_big) 
    end
  end

  module ActiveModel::Validations::HelperMethods
    def validates_soggetti(*attr_names)
      validates_with SoggettiValidator, _merge_attributes(attr_names)
    end
  end

 end

Model

class Bozza < ActiveRecord::Base
  attr_accessible :height, :quantita, :soggetti, :width

  validates_presence_of :height, :width, :quantita
  validates_numericality_of :height, :width
  validates_numericality_of :quantita, :only_integer => true
  validates_numericality_of :soggetti, :only_integer => true

  validates_soggetti :soggetti
end

Edited error message for YAML tables and a rails.validations.customValidators.js file Also tried by adding, in application.js

//= require rails.validations.customValidators

Only the custom validation will not kick in. I am assuming the issue is with the module definition.

4

1 回答 1

0

通过在 /lib 下创建带有模块语句的 validations_helpers.rb 文件来解决。

  module ActiveModel::Validations::HelperMethods
    def validates_soggetti(*attr_names)
      validates_with SoggettiValidator, _merge_attributes(attr_names)
    end
  end

并在相关控制器中调用模块。

模型还需要指定 rails3 方式:

  validates :height, :presence => true, :numericality => true
  validates :width, :presence => true, :numericality => true
  validates :quantita, :presence => true, :numericality => {:only_integer => true}
  validates :soggetti, :soggetti => true, :numericality => {:only_integer => true}

这与https://github.com/bcardarella/client_side_validations上的说明略有不同, 后者建议 validates_myCustomValidation

于 2013-07-14T10:16:32.197 回答