开发者

Rails 3 vanity URLs with url_for integration

I would like vanity URLs for the #show action on one of my controllers. I've setup this route:

match "/:username" => "users#show", as: :show_user

I would really like to be abl开发者_如何学编程e to use this vanity URL with the standard way to link to a user show, like so:

link_to("foo", user)

Thanks!


Jesse Wolgamott has the right idea but a couple notes...

this should go at the bottom of routes.rb so that it doesn't clobber any other routes

resources :users, :path => '/'

UsersController#show

@user = User.where(:username => params[:id])


One (slightly verbose) way to do this with your current route setup is

link_to "foo", show_user_path(user)

Alternatively,

  • You could name your route 'user instead' of 'show_user'. And then override the provided show_user_url(user) helper to use user.username instead of user.id
  • Under the covers link_to calls polymorphic_url, which calls build_named_route_call you could monkey-path build_named_route to call your custom route instead of the regular user_url.

Unfortunately, there is no public api/configuration to make this happen cleanly.


routes.rb

resources :users, :path => '/'

user.rb

def to_param
  username.parameterize
end

If there is a username of Bob, then <%= link_to user.username, user%> will create

<a href="/bob">Bob</a>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜