开发者

How to escape link_to :id value in Rails 2.3.5

开发者 https://www.devze.com 2023-03-13 17:51 出处:网络
On Rails 2.3.5 I have a view that public information about a user that lives at a URL like this: http://www.mysite.com/users/johndoe

On Rails 2.3.5

I have a view that public information about a user that lives at a URL like this:

http://www.mysite.com/users/johndoe

My route:

map.connect 'members/:id', :controller => "users", :action => "showmember"

I never want to expose the int IDs for users so I use the username as the id for that view.

When I link to it:

<%=link_to user.username, :controller => 'users', :action => 'showmember', :id => user.username %>

Everything is fine except if the username happens to include chars that need to b开发者_如何转开发e escaped. What's the best way to escape the id in link_to?


CGI::escape(user.username)

that method will URI-encode the value so it's safe in the URL. Does Rails not do it automatically? Did you try not escaping and putting crazy characters in it?

Edit, and the opposite version:

CGI::unescape(params[:id])

Although I still feel like rails might handle it automatically for you. Might want to test.

Edit again:

Rails does have a .parameterize method so: user.username.parameterize will make a string url-friendly, it's documented here: http://apidock.com/rails/v3.0.7/String/parameterize

The main problem with this is that if you have 2 usernames: my.user and myuser they will both parameterize to the same string myuser

I think the accepted way of doing it is (as the doc example shows) like this:

"#{user.id}-#{user.username.parameterize}"

this way if you do User.find(params[:id]) it strips out everything after the first number and just uses that as the id. There are gems that will make a unique parameter-friendly string for you to use if you're really that against having the user id in the params (Is there a reason for this concern?). One such gem is friendly_id: https://github.com/norman/friendly_id/ although there are others. The idea is that there's another field on your model specifically for url's, and it's auto-generated on before_create based off of your username field. It has to be unique and parameter friendly, which the gem takes care of.

Hopefully this answer helps you out more :p


The issue wasn't with escaping I ended up adjusting the route based on this question:

Rails query string with a period (or full stop).

0

精彩评论

暂无评论...
验证码 换一张
取 消