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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
amaseuk
  • 2,147
  • 4
  • 24
  • 43

2 Answers2

9

You can use ActiveSupport's parameterize method:

def to_param
  name.parameterize
end
John Topley
  • 113,588
  • 46
  • 195
  • 237
1

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

Community
  • 1
  • 1
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398