我使用的是rubyonrails4.2,我想通过在anamespace
块中使用scope :module
或scope :path
/resource
来路由“嵌套”路径。
也就是说,我有以下路线:
resources :users, :only => [:show]
那场比赛
user_path GET /users/:id(.:format) users#show
我想匹配以下路径
users_sessions_path POST /users/sessions users/sessions#create
user_session_path GET /users/:id/session users/sessions#show
delete_user_session_path GET /users/:id/session/delete users/sessions#delete
user_session_path DELETE /users/:id/session users/sessions#destroy
我读了official documentation然后想说
resources :users, :only => [:show] do
scope :module => :users do
scope :module => :sessions do
# scope :path => :sessions do
# namespace :sessions do
...
end
end
end
但没有成功的尝试。我该如何说明路线?
@dgilperez应答后更新
我试过下面的代码
resources :users, :only => [:show] do
scope :module => :users do
resource :session, :only => [:show, :new, :create, :destroy] do
get :delete, :on => :collection, :to => 'sessions#delete'
end
end
end
那场比赛
delete_user_session_path GET /users/:user_id/session/delete(.:format) users/sessions#delete
new_user_session_path GET /users/:user_id/session/new(.:format) users/sessions#new
user_session_path POST /users/:user_id/session(.:format) users/sessions#create
user_session_path GET /users/:user_id/session(.:format) users/sessions#show
DELETE /users/:user_id/session(.:format) users/sessions#destroy
但我仍然需要映射
new
和create
操作,而不需要传递:user_id
参数。也就是说,我想绘制一些new_user_session_path GET /users/session/new(.:format) users/sessions#new
user_session_path POST /users/session(.:format) users/sessions#create
最佳答案
我认为您过度复杂了:您不需要使用scope
或path
来呈现嵌套资源。你只要把它们窝起来:
resources :users, :only => [:show] do
resources :sessions
end
将呈现以下路径:
user_sessions GET /users/:user_id/sessions(.:format) sessions#index
POST /users/:user_id/sessions(.:format) sessions#create
new_user_session GET /users/:user_id/sessions/new(.:format) sessions#new
edit_user_session GET /users/:user_id/sessions/:id/edit(.:format) sessions#edit
user_session GET /users/:user_id/sessions/:id(.:format) sessions#show
PATCH /users/:user_id/sessions/:id(.:format) sessions#update
PUT /users/:user_id/sessions/:id(.:format) sessions#update
DELETE /users/:user_id/sessions/:id(.:format) sessions#destroy
user GET /users/:id(.:format) users#show
这些不是您提到的您需要的路由,但我希望您重新考虑是否确实需要这样的路由,使用命名空间控制器和自定义名称(如
delete_user_
),或者您更喜欢使用标准的路由。如果你真的需要这些确切的路线,请告诉我。OP更新后更新
要想让这两条路径丢失,你需要把它们从休息资源中取出。我直接这样写:
resources :users, :only => [:show] do
scope :module => :users do
resource :session, :only => [:show, :destroy] do
get :delete, :on => :collection, :to => 'sessions#delete'
end
end
end
get 'users/session/new', to: 'users/sessions#new', as: :new_user_session
post 'users/session', to: 'users/sessions#create'
关于ruby-on-rails - 如何通过使用“命名空间”或“scope:module”/`scope:path`来路由“嵌套”路径?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28401887/