4

i want to call active record validation method in my custom validation method like

class Asset < ActiveRecord::Base
  validate :ensure_unique_identification_code
  validates :name,:uniqueness=>true

 def ensure_unique_identification_code
   self.identifier="identifier code" #code is generated using some helper method of Asset model
  validates :identifier ,:uniqueness=>true

 end
end

give error

undefined method `validates' for #<Asset:0xb6692dbc>

how can we call validation methods in instance methods of a model

Naveed
  • 11,057
  • 2
  • 44
  • 63
  • This probably isn't the solution, but are you sure you're using Rails 3? Validates is unique to 3, typically when that error occurs, people are still at 2.3. – a3uge Apr 14 '11 at 17:59
  • yes i am on rails 3 rails -v =>Rails 3.0.4 – Naveed Apr 15 '11 at 04:22
  • use "validates_uniqueness_of :identifier" instead and a before_validation filter for your custom code. – jvatic Apr 16 '11 at 01:08

2 Answers2

0

May be you are using a new version of Rails (3.x.x) (rails -v) but you still have an old Rails application... You should generate a Rails application in another folder and then move your files .rb, views, and so on in your new app/ folder... I confirm that "validates is unique to 3, typically when that error occurs, people are still at 2.3" like a3uge said.

0

You can instanciate a specific validator and call validate() method directly:

def age_validation
  ActiveModel::Validations::NumericalityValidator.new(
    :greater_than_or_equal_to => 0,
    :less_than_or_equal_to => 100,
    :attributes => :age
  ).validate(self)
end
Gus
  • 942
  • 9
  • 32