ruby on rails-定义custon命名路由



如何定义路线,以获得以下结果:

 new_ad GET    /ads/new/:type(.:format)        ads#new
    ads POST   /ads(.:format)                  ads#create
edit_ad GET    /ads/:id/edit(.:format)         ads#edit
     ad GET    /ads/:id(.:format)              ads#show
        PUT    /ads/:id(.:format)              ads#update
        DELETE /ads/:id(.:format)              ads#destroy

一般来说,我需要在新路径中指定类型param,并能够使用这样的路径助手:

new_ad_path("somytype") # -> ads/new/somytype -> ads#new -> params[:type] = "somytype"

在您的路线中。rb

get '/ads/new/:type' => 'ads#new', as: :new_ad

@mind.blank的解决方案也能很好地进行

要传入参数,您需要执行以下操作:

new_ad_path(type: "sometype")

这将导致:

/ads/new?type=sometype

然后在控制器中,您可以检查参数类型并对其执行任何需要的操作。

您可以使用定义这些路线

resources :ads, except: [:index, :new] do
  get '/ads/new/:type', on: :collection, as: :new_ad
end

最新更新