Question

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.

Was it helpful?

Solution

Resolved by creating under /lib a validations_helpers.rb file with the module statement.

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

and calling the module in relevant controllers.

also the model needs to specify the rails3 way:

  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}

which is slightly different from the instructions on https://github.com/bcardarella/client_side_validations which suggests validates_myCustomValidation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top