0

I have a Rails application that lists different teams in a list on one the views. The teams are links and used in the URL, for example localhost:3000/teams/chelsea shows "chelsea".

If I have a team called man utd when I click the link it escapes all the spaces so the URL is like:

localhost:3000/teams/<script>man%20utd

but I just it want it to be

localhost:3000/teams/<script>man utd

This is my code:

   <a href="/<%= team["name"].html_safe %>"><%= team["name"] %></a>

I tried using html_safe after reading other questions and also raw but have had no luck with them.

What is the best way to solve this problem?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user2527785
  • 97
  • 1
  • 1
  • 12
  • 2
    That's not HTML escaping, that's URL encoding. You can't put a space in a URL. Rails should be able to manage for static URLs, can you post config/routes.rb – Slicedpan Aug 19 '13 at 09:02
  • What Slicedpan says is correct. This has nothing to do with Ruby or Rails. Your browser encodes the URL automatically and there is nothing you can do to prevent that. – Mischa Aug 19 '13 at 09:09
  • It also changes < to /%3 what is the best way to handle this? Should I stop the user enter spaces and < for the team name on the client side? or which way would be more correct? – user2527785 Aug 19 '13 at 09:14
  • Best practice is to not use URLs that contain spaces or other characters that require escaping. User input validation is a whole different question. – Slicedpan Aug 19 '13 at 09:41

1 Answers1

0

I wouldn't put any spaces in your URLs - do it as "man-utd" instead. See Spaces in URLs?

There are also more Rails-y ways to write out your links. If your teams are a database model I'd write them out as:

<% @teams.each do |team| %>
   <%= link_to team.name, team %>
<% end %>  

But that will link to /teams/1 and teams/2 etc and you'll have to put in a specific route to map /teams/chelsea to /teams/1.

If you've just done them as separate views for man utd and chelsea then do:

<%= link_to 'Man Utd', :controller => 'teams', :action => 'man-utd' %>
<%= link_to 'Chelsea', :controller => 'teams', :action => 'chelsea' %>
Community
  • 1
  • 1
Chris Lewis
  • 1,315
  • 10
  • 25