Dynamic named route prefix, how to? [Update: Solved]

I wonder how to create a named route prefix without any changes to route helpers. Something like

scope ':current_user.name' do
  resources :articles
end

Where current_user is taken from ApplicationController from currently logged in user, so that articles_path would produce /bob/articles for user Bob and /john/articles for user John, and both urls would point to Articles#index

Articles is a closed resource available to logged in users only. I’d prefer to keep helpers as articles_path and not to change it to user_articles_path

Is it possible? Thanks

It seems you want a nested structure of articles under users. You could override to_param on user and return an url safe string for the user name. It might be better to use a gem like friendly_id to handle this. If you google for vanity urls in rails you will probably find several approaches to get this working.

Hope this helps.

@pedrosmmoreira, thanks but it won’t help. Nested routes with a slug will generate routes like /users/bob/articles instead of /bob/articles and helpers like user_articles_path instead of articles_path

You can match the segments by hand, as in

get "/:user_name/articles", to: "some_controller#action", as: :whatever_you_want

Then using one of the approaches above can help you pick the url segment and retrieve a record in the way you intend. I’d be careful with this though since, to an extent, you are kind of overriding the canonical RESTful representation of resources (or at least, I get that feeling)

I’d prefer to keep them restful.

basically i have a working app, i just want to prefix all current routes with current_user.name in url. Without having to rewrite all routes in non restful manner or changing all url helpers like from articles_path, posts_path, profile_path, etc to user_articles_path, user_posts_path, user_profile_path.

scope 'user' do
  resources :articles, :posts, :profile, etc
end

This adds /user/* scope to all my restful routes transparently without making me change any url helper. I think there should be a way to provide dynamic scope prefix instead of fixed /user/*

Solution:

scope ':user' do
  resources :articles, :posts, :profile, etc
end

Rails would expect :user parameter in urls like

articles_path user: current_user.name.parameterize

Instead in ApplicationController we can set default user option

def default_url_options options={}
  options.merge(user: current_user.name.parameterize)
end

And intended result achieved: articles_path generates /bob/articles

Source: stackoverflow

@pedrosmmoreira, thanks for trying to help

No worries, glad you got it solved.