Replace space with dash before save using Rails 3

Another option would be to us regexp and replace all existing spaces with. You'd put something along the lines of:

self.firstname.gsub(/\s+/, '-')

in your model.

Note: I'm not sure if ruby accepts \s as "any whitespace character" And I think the * should make sure that if someone enters a name with two neighbour spaces(or more) it won't convert each space into a separate dash, but only into one.


Why don't you just have first_name and last_name columns in the db, and create your own validation rule to make sure the combination is unique (http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods). You should also create a unique index over those two columns in your db.


You can use ActiveSupport's inflector method parameterize on the string.

name = 'john smith'     # => john smith
name.parameterize       # => john-smith

Further, parameterize takes an option to use for the word-break, so you can replace the dash with an underscore like this:

name.parameterize("_")  # => john_smith

An advantage of using parameterize is that it normalizes the characters to the latin, so...

name = "jöhanne såltveç"
name.parameterize       # => johanne-saltvec

EDIT: As of Rails 5.0.0.1 the separator needs to be passed as an option. Therefore: name.parameterize(separator: '_')