簡體   English   中英

Rails - 自定義資源路由

[英]Rails – Custom Resource Routes

我正在嘗試自定義我的節目路線...我不希望用戶能夠通過以下方式查看項目:id ...

我有一個銷售模型,展示路線是:

sale GET    /sales/:id(.:format)     sales#show

但是,我不希望用戶能夠通過id查看銷售,相反,我希望它是:

sale GET    /sales/:guid(.:format)     sales#show

guid是我在創建對象時生成的uuid:

def populate_guid
    self.guid = SecureRandom.uuid()
end

在config / routes.rb中

get '/sales/:guid', to: 'sales#show'

或者如果您使用rails 4,您可以:

resources :sales, param: :guid

在控制器中

def show
  @sale = Sale.find(params[:guid])
end

您可以在routes.rb中定義自定義路由:

get "/sales/:guid", :to => "sales#show"

然后在你的控制器中,對於show動作,你可以從url中傳遞的guid中找到你想要的銷售:

def show
  @sale = Sale.find_by_guid(params[:guid])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM