这让我很难过!
我们说我有一个story
课程。
普通用户可以创建故事,查看故事并删除属于他们的故事。
管理员用户可以创建故事,查看所有故事并删除所有故事。
我想在网址结构中使用管理区域:
/control_panel/stories # list all stories in the site
/control_panel/stories/new # create a new story
/control_panel/stories/:id # show, edit, update, delete story (via different request methods)
但是,我也希望用户拥有这些路线:
/stories
/stories/new
/stories/:id
我不知道如何实现这一点。试图创建路线一直是个噩梦。这个配置:
resources :stories
scope '/control_panel' do
resources :stories
end
几乎就在那里:
stories GET /stories(.:format) stories#index
POST /stories(.:format) stories#create
new_story GET /stories/new(.:format) stories#new
edit_story GET /stories/:id/edit(.:format) stories#edit
story GET /stories/:id(.:format) stories#show
PATCH /stories/:id(.:format) stories#update
PUT /stories/:id(.:format) stories#update
DELETE /stories/:id(.:format) stories#destroy
GET /control_panel/stories(.:format) stories#index
POST /control_panel/stories(.:format) stories#create
GET /control_panel/stories/new(.:format) stories#new
GET /control_panel/stories/:id/edit(.:format) stories#edit
GET /control_panel/stories/:id(.:format) stories#show
PATCH /control_panel/stories/:id(.:format) stories#update
PUT /control_panel/stories/:id(.:format) stories#update
DELETE /control_panel/stories/:id(.:format) stories#destroy
但是,我在control_panel路线的指定路线在哪里?!我预计:
GET /control_panel/stories
名称为control_panel_stories
(与其对应的非命名空间路由/stories)
一样,
GET /control_panel/stories/new
名称为new_control_panel_story
GET /control_panel/stories/:id/edit
名称为edit_control_panel_story
和
GET /control_panel/stories/:id
名称为control_panel_story
相反,我没有命名路线!
namespace :control_panel
代替scope 'control_panel'
,我会得到我的命名路线:resources :stories
namespace :control_panel do
resources :stories
end
给了我:
control_panel_stories GET /control_panel/stories(.:format) control_panel/stories#index
POST /control_panel/stories(.:format) control_panel/stories#create
new_control_panel_story GET /control_panel/stories/new(.:format) control_panel/stories#new
edit_control_panel_story GET /control_panel/stories/:id/edit(.:format) control_panel/stories#edit
control_panel_story GET /control_panel/stories/:id(.:format) control_panel/stories#show
PATCH /control_panel/stories/:id(.:format) control_panel/stories#update
PUT /control_panel/stories/:id(.:format) control_panel/stories#update
DELETE /control_panel/stories/:id(.:format) control_panel/stories#destroy
app/controllers/control_panel/stories_controller.rb
scope
d路线有什么意义呢?它们似乎毫无意义。答案 0 :(得分:1)
尝试:
scope :path => 'control_panel', :as => 'control_panel' do
例如,您希望管理员能够销毁,而不是普通用户:
def destroy
return redirect_to(:back, :notice => 'You need to be admin to delete.') if current_user.regular?
...
end
答案 1 :(得分:1)
关于路由范围和命名空间,您应该看看这个article