Automatic string trimming on ActiveRecord save

Howdy.

Is there an easy way to get ActiveRecord to trim/strip spaces off
strings before inserting them into the database?

I can’t think of a good reason that one would want trailing spaces to
persist in string database columns. I know I can iterate through all
my class members and strip them before the save, but that seems like
comparatively low level work considering the high level feel of
ActiveRecord. (It makes me suspect there’s a better way)

Thanks,
Michael

michael_teter wrote:

Howdy.

Is there an easy way to get ActiveRecord to trim/strip spaces off
strings before inserting them into the database?

I can’t think of a good reason that one would want trailing spaces to
persist in string database columns. I know I can iterate through all
my class members and strip them before the save, but that seems like
comparatively low level work considering the high level feel of
ActiveRecord. (It makes me suspect there’s a better way)

Thanks,
Michael

Yes you can make it with metaprogramming, but you should see at the
active record source and then make a new method that run before a record
is created

Check this gem GitHub - holli/auto_strip_attributes: AutoStripAttributes gem for Rails helps to remove unnecessary whitespaces from ActiveRecord or ActiveModel attributes. It's good for removing accidental spaces from user inputs (e.g. when user copy/pastes some value to a form and the value has extra spaces at the end).
It’s not completely automated, but makes it much easier than having to code it on a case by case basis

1 Like