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