Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace space with dash before save using Rails 3

I am trying to save a name to the database and a single word (firstname) works fine but when the user enter both firstname and lastname I want Rails to save it to the database as firstname-lastname instead of firstname lastname (space between).

I know I perhaps should use a before create filter but I am not sure how this need to look like. I want the validation to work to, i.e. no two people should be able to use the same name.

I am using Rails 3.

like image 652
Jonathan Clark Avatar asked Dec 17 '10 09:12

Jonathan Clark


1 Answers

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: '_')

like image 93
IAmNaN Avatar answered Jan 01 '23 06:01

IAmNaN