Friendly URLs in Rails 3
My current a开发者_如何转开发pp is using URLs like:
/philsturgeon /philsturgeon/trip_slug
I have trips attached to users in my model like so:
class Trip < ActiveRecord::Base
belongs_to :user
def to_param
"#{user.username}-#{slug}"
end
end
Now I have been told about to_param which seems awesome. It means I can use the normal resource linking:
<h4><%= link_to trip.name, trip %></h4>
instead of manually creating strings like this:
redirect_to('/' + current_user.username + '/' + @trip.slug)
Problem is that gives me a hyphen (or dash) separated URL. As soon as I change the URL to_param to #{user.username}/#{slug}
(notice the slash instead of the dash) I get an error:
ActionController::RoutingError in Home#index
Showing /Users/phil/Scripts/ruby/travlr/app/views/home/index.html.erb where line #27 raised:
No route matches {:action=>"destroy", :controller=>"trips", :id=>#}
Extracted source (around line #27):
24: <%= gravatar trip.user.email, 50 %> 25: 26: 27: <%= link_to trip.name, trip %> 28: 29: 30:
User:
You need to escape the /
to %2F
. So you should have ...
def to_param
"#{user.username}%2F#{slug}"
end
Looks like hard-coding the URI is the only real solution in this situation. Works fine, but not the nicest code.
Thanks to those who answered, but they weren't quite correct.
This is happening because '/' has special meaning with reference to URLs. Imagine you have a file in /Home/user/my-file and you try to access it using file://Home/user/my/file
This is basically what you are trying to do. If you want 'file' to be inside 'my' you'll need to store it in there. In the case of Rails you'll need to make a nested resource.
精彩评论