Peter Marklund's Home |
Rails Hack: Auto Strip ActiveRecord Attributes
We have a user who unintentially enters a space after his email address. It seems that a lot of times it makes sense to automatically strip ActiveRecord model attributes before they are validated. Inspired by this post I came out with my own auto_strip method that adds a before validation callback which seems less intrusive than redefining the attribute setter method:
# Sometimes users accidentally enter space before or after text in text fields. Let's not punish them
# with an error message for this.
attributes.each do |attribute|
before_validation do |record|
record.send(" =", record.send(" _before_type_cast").to_s.strip) if record.send(attribute)
end
end
end
end
end
Now in my ActiveRecord model I can say for example:
Maybe auto stripping would be useful as an option to the Rails validation macros?