ruby-on-railsruby-on-rails-4before-filterbefore-save

before_save, strip a string


I'm trying to strip the whitespaces of the variable Username in my User Model.

I'm using

before_save do
  self.username.strip!
end

but it doesn't seem to work, am i missing something ?


Solution

  • You'd rather update the setter instead of polluting your model with callbacks:

    def username=(value)
      self[:username] = value.to_s.strip
    end
    

    Btw, I prefer squish