[英]Add a 'destroyAll' action and route to my RESTful rails app
[英]How to add a custom RESTful route to a Rails app?
我正在讀這兩頁
Rails指南頁面顯示
map.resources :photos, :new => { :upload => :post }
及其相應的URL
/photos/upload
這看起來很精彩。
我的routes.rb
顯示了這一點
map.resources :users, :new => { :signup => :get, :register => :post }
當我這樣做: [~/my_app]$ rake routes
我看到添加了兩條新路線
signup_new_user GET /users/new/signup(.:format)
register_new_user POST /users/new/register(.:format)
注意包含/new
! 我不希望這樣。 我只想要/users/signup
和/users/register
(如Rails Routing Guide中所述)。
有幫助嗎?
將控制器公開為資源時,將自動添加以下操作:
show
index
new
create
edit
update
destroy
這些操作可以分為兩組:
:member
行動 成員操作的URL具有目標資源的id。 例如:
users/1/edit
users/1
您可以將:member
操作視為類的實例方法。 它始終適用於現有資源。
默認成員操作: show
, edit
, update
, destroy
:collection
行動 :collection
操作的URL不包含目標資源的id。 例如:
users/login
users/register
您可以將:collection
操作視為類的靜態方法。
默認集合操作: index
, new
, create
在您的情況下,您需要兩個新的注冊操作。 這些操作屬於:集合類型(因為您在提交這些操作時沒有用戶的ID)。 您的路線如下:
map.resources :users, :collection => { :signup => :get, :register => :post }
操作的URL如下:
users/signup
users/register
如果要刪除Rails生成的標准操作,請使用:except /:only options:
map.resources :foo, :only => :show
map.resources :foo, :except => [:destroy, :show]
編輯1
我通常將confirmation
操作視為:member
操作。 在這種情況下, params[id]
將包含確認碼。
路線配置:
map.resources :users, :member => { :confirm => :get}
網址
/users/xab3454a/confirm
confirm_user_path(:id => @user.confirmation_code) # returns the URL above
調節器
class UsersController < ApplicationController
def confirm
# assuming you have an attribute called `confirmation_code` in `users` table
# and you have added a uniq index on the column!!
if User.find_by_confirmation_code(params[id])
# success
else
# error
end
end
end
這可以作為另一種語法 - 有些可以知道。
語法1:
resources :users do
member do
get 'signup'
post 'register'
end
end
耙路輸出將包括
signup_users GET /users/signup(.:format) {:action=>"signup", :controller=>"users"}
register_users POST /users/register(.:format) {:action=>"register", :controller=>"use
RS“}
語法2:如果只有一個收集路由
resources :users do
get 'signup', :on => :collection
end
如果我正確理解你的問題,你只需要重命名new
的url並create
動作。
這將是這樣做的:
map.resources :users, :path_names => {:new => 'signup', :create => 'register'}
如果你真的想添加具有相應控制器動作的新路線,那么Damiens的答案就是要走的路。
new
選項允許您創建用於創建新對象的新路徑。 這就是為什么他們以該術語為前綴。
您正在尋找的是:collection
選項。
map.resources :users, :collection => { :signup => :get, :register => :post }
這將創建/users/signup
和/users/register
urls。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.