views:

27

answers:

2

I am using a user input string to create a url and I only want the url to contain lowercase letters and hyphens

e.g. example.com/this-is-a-url

In my model, I have added so far:

  def to_param
      name.downcase.gsub(" ", "-")
  end

This makes it lowercase and hyphenated. How can I remove all illegal characters, such as '/"$£%& and so on? A regular expression might be the answer but is there something built in for this purpose already in Rails?

Perhaps instead of doing the above, I should create a validation that makes sure that 'name' is only spaces and letters? Is there something built in for this purpose?

+1  A: 

You might consider the to_slug plugin for this. See also this related question.

Mark Rushakoff
+4  A: 

You can use ActiveSupport's parameterize method:

def to_param
  name.parameterize
end
John Topley
I'm surprised this wasn't in the question I linked to. +1 for the builtin approach.
Mark Rushakoff