dimanche 26 avril 2015

add method to ActiveRecord::Base

I am reading rails guides. There is a example that I don't know how to do working. Can Someone to explain me how to do it working and what is the functionality of this example. I am newbie in rails

You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:

ActiveRecord::Base.class_eval do
  def self.validates_as_choice(attr_name, n, options={})
    validates attr_name, :inclusion => { { :in => 1..n }.merge!(options) }
  end
end

Simply reopen ActiveRecord::Base and define a class method like that. You’d typically put this code somewhere in config/initializers. You can usethis helper like this

class Movie < ActiveRecord::Base
  validates_as_choice :rating, 5
end

Aucun commentaire:

Enregistrer un commentaire