¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita0
Is it possible to extend accessor methods to include validation routines?
How can one include validation routines to attr_write and attr_accessor?
1 Respuesta
0
Yes, you can 'Monkey Patch' the attr_* methods and modify it's behavior, but that's not a good idea. ( google 'monkey patching in ruby' )
Instead, it's good to write custom getter and setters to serve your purpose
Here's an example
--------------------------------------------------------------------------------
class Person < ActiveRecord::Base
# don't use attr_accessible here as it interferes/duplicates the methods below
# setter
def shirt=(value)
write_attribute(:shirt_fee_in_cents, value)
end
# getter
def shirt
if self[:shirt].present?
return self[:shirt]
end
AverageHuman.default_shirt
end
--------------------------------------------------------------------------------
Example taken from
https://richardcooke.info/how-to-make-a-custom-getter-setter-for-activerecord-ruby-on-rails-attributesproperties/