我正在使用Ruby on Rails 3.0.7,在我的应用程序中,我有一个Users::Article
类(注意它是命名空间的)。在routes.rb
文件中,声明如下:
resources :users do
resources :articles
end
我想设置与Users::Article
类相关的路线,以便我可以在网址/articles
,/articles/new
,/articles/1
和{{1}处访问该路线但我仍然希望使用RoR 约定优于配置“系统”。也就是说,我想用:
/articles/1/edit
; Users::ArticlesHelper
查看文件; views/users/articles/<file_name>.html.erb
和<name>_path
); 我该怎么做?
简而言之,例如,我想引用<name>_url
路径,但要使应用程序完全按照/articles/1
路径运行。
答案 0 :(得分:0)
这不是一个问题,但它与路由参数有关。
您可以使用/articles/:id
然后引用控制器内的所有者(用户)。
在第二种情况下/users/:user_id/articles/:id
将2个参数传递给控制器。
答案 1 :(得分:0)
来自ActionDispatch::Routing::Mapper::Resources docs:
:shallow
# Generates shallow routes for nested resource(s). When placed on a parent
# resource, generates shallow routes for all nested resources.
resources :posts, :shallow => true do
resources :comments
end
# Is the same as:
resources :posts do
resources :comments, :except => [:show, :edit, :update, :destroy]
end
resources :comments, :only => [:show, :edit, :update, :destroy]
# This allows URLs for resources that otherwise would be deeply nested such as a
# comment on a blog post like /posts/a-long-permalink/comments/1234 to be
# shortened to just /comments/1234.
答案 2 :(得分:0)
从&gt; rake routes
获取此信息users_articles GET /articles(.:format) {:action=>"index", :controller=>"users/articles"}
POST /articles(.:format) {:action=>"create", :controller=>"users/articles"}
new_users_article GET /articles/new(.:format) {:action=>"new", :controller=>"users/articles"}
edit_users_article GET /articles/:id/edit(.:format) {:action=>"edit", :controller=>"users/articles"}
users_article GET /articles/:id(.:format) {:action=>"show", :controller=>"users/articles"}
PUT /articles/:id(.:format) {:action=>"update", :controller=>"users/articles"}
DELETE /articles/:id(.:format) {:action=>"destroy", :controller=>"users/articles"}
我们在routes.rb
中需要这个namespace :users, :path => '' do
resources :articles
end
注意:我正在使用:名称空间,因为这就是你所说的。
希望这有帮助。