Can controller names in RESTful routes be optional?

爷,独闯天下 提交于 2019-12-03 08:54:51

You're looking for the :path_prefix option for resources.

map.resources :users do |user|
  user.resources :blogs do |blog|
    blog.resources :posts, :path_prefix => '/:user_login/:blog_title/:id'
  end
end

Will produce restful routes for all blogs of this form: site.org/pavelshved/bogging-horror/posts/1234. You'll need to go to a little extra effort to use the url helpers but nothing a wrapper of your own couldn't quickly fix.

The only way to get rid of the posts part of the url is with named routes, but those require some duplication to make restful. And you'll run into the same problems when trying to use route helpers.

The simplest way to get what you want would be to create a route in addition to your RESTful routes that acts as a shorthand:

map.short_blog ':user_id/:blog_id/:id', :controller => 'posts', :action => 'show'

You'll have to change the URL bits to work with how you're filtering the name of the user and the name of their blog. But then when you want to use the shorter URL you can use all the short_blog_* magic.

Straight out of the default routes.rb:

map.connect 'products/:id', :controller => 'catalog', :action => 'view'

You could write:

map.connect ':user_id/:blog_id/:id', :controller => 'posts', :action => 'show'

But be sure to include that in the very end of the file, or it will try to match every three levels deep url to it.

Try this

map.pavelshved '/pavelshved/', :controller => :users, :action => view or
map.pavelshved '/:id', :controller => :users, :action => show do | blogs|
  blogs.bloging '/:id', :controller => :blogs, :action => show do | post|
    post.posting '/:id', :controller => :posts, :action => show
  end
end

I hope it work :)

Google "rails shallow routes" for information about this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!