Вопрос

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 ?

Это было полезно?

Решение

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

Другие советы

If you want to remove only leading and trailing white space you can use .strip!

But as you said:

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

I think actually you want to remove all spaces following should do:

.gsub(/\s+/, "")

EDIT:

Oh yes, You can also use Rail's built-in method squish()

thanx to apneadiving for reminding

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top