路径根级别的嵌套资源

时间:2009-09-25 00:29:41

标签: rest ruby-on-rails-2

我正在尝试创建一个带有url方案的嵌套资源:“http://example.com/username/...”。

我现在拥有的是:

ActionController::Routing::Routes.draw do |map|
  map.home '/', :controller => 'home'

  map.resource :session

  map.resources :users, :has_many => :nodes
  #map.user '/:id', :controller => 'users', :action => 'show', :has_many => :nodes

  map.resources :nodes, :belongs_to => :user
end

这会产生以下网址:

http://example.local/users/username
http://example.local/users/username/nodes

如何避免“用户”前缀超出我的范围。将“as: => ''”选项传递给map.resources不起作用,并且命名路由似乎不支持“:has_many”或“:belongs_to”选项。

评论“map.resources :users”并取消后面的“map.user”行似乎有用......直到您到达嵌套资源。然后它吐出以下错误:

undefined method `user_nodes_path' for #<ActionView::Base:0x1052c8d18>

我知道这个问题以前出现过很多次,并且总是遇到“你为什么要这样做?”响应。坦率地说,Twitter做到了,Facebook做到了,我也想这样做! ;-D

至于如何避免用户名来自冲突的内置路径的常见批评,我将最小用户名长度设置为6个字符,并计划使所有内置根级路径将路径分段5个字符或更短(即“/opt/...”表示选项,“/in/...”表示会话登录等。

2 个答案:

答案 0 :(得分:1)

正如这个问题所述:

Default segment name in rails resources routing

你应该可以使用这个插件:

http://github.com/caring/default_routing

或者,您可以使用

等手动指定它们
map.users     '/users',     :controller => 'users', :action => 'index',
  :conditions => { :method => :get }
map.connect   '/users',     :controller => 'users', :action => 'create',
  :conditions => { :method => :post }
map.user      '/:id',       :controller => 'users', :action => 'show',
  :conditions => { :method => :get }
map.edit_user '/:id/edit',  :controller => 'users', :action => 'edit',
  :conditions => { :method => :get }
map.new_user  '/users/new', :controller => 'users', :action => 'new',
  :conditions => { :method => :get }
map.connect   '/:id', :controller => 'users', :action => 'update',
  :conditions => { :method => :put }
map.connect   '/:id', :controller => 'users', :action => 'destroy',
  :conditions => { :method => :delete }

map.resources :nodes, :path_prefix => '/:user_id', :name_prefix => 'user_'
# to generate user_nodes_path and user_node_path(@node) routes

这样或类似的东西应该从map.resources为您提供您想要的东西。

  

map.resources不起作用,似乎命名路由不支持“:has_many”或“:belongs_to”选项。

命名路由支持has_many,用于向URL路径添加另一个资源级别。例如

map.resources :users, :has_many => :nodes

生成所有users_pathuser_nodes_path路由,例如/users/users/:id/users/:id/nodes/users/:id/nodes/:id。它与

完全相同
map.resources :users do |user|
  user.resources :nodes
end
  

注释掉“map.resources:users”并在它看起来有用之后解开“map.user”行...直到你到达嵌套资源。然后它吐出以下错误:

undefined method `user_nodes_path' for #<ActionView::Base:0x1052c8d18>

那是因为map.resources :users, :has_many => :nodes生成了这些路线。 map.user '/:id', :controller => 'users', :action => 'show'只生成一条命名路线,而user_path

答案 1 :(得分:0)

this related question

中查看我的回答

基本上,你可以通过:path => ''作为选项来否定识别段(仅在Rails 3中测试)。请注意,这可能会与其他路由模式发生冲突,因此请注意放置它的位置和方式。

相关问题