Domanda

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 ?

È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top