如何在Ruby on Rails中创建自定义路由 - 4.2

时间:2016-09-13 06:05:46

标签: ruby-on-rails

现在我的路线如下;

resources :invoices do
  collection do
    match 'search' => 'invoices#search', via: [:get, :post], as: :search
  end
end

但我希望' deliveryies#search' 而不是'发票#search'

我成功为以下路线定制;

get 'deliveries', to: 'invoices#index', as: :deliveries

get 'deliveries/new', to: 'invoices#new', as: :delivery

get 'deliveries/:id/edit', to: 'invoices#edit', :as => :del

我已经尝试但无法为' deliveryies#search'。

进行自定义

欢迎任何建议。

提前谢谢。

2 个答案:

答案 0 :(得分:1)

按如下方式更改路线

resources :deliveries, controller: 'invoices', only: [:index, :new, :edit]
resources :deliveries, only: [] do
  collection do
    get :search
    post :search
  end 
end

这将为您生成以下路线:

        deliveries GET  /deliveries(.:format)           invoices#index
      new_delivery GET  /deliveries/new(.:format)       invoices#new
     edit_delivery GET  /deliveries/:id/edit(.:format)  invoices#edit
search_deliveries  GET  /deliveries/search(.:format)    deliveries#search
                   POST /deliveries/search(.:format)    deliveries#search

修改

根据你的评论,我认为你只需要使用不同的控制器

试试这个

resources :deliveries, controller: 'invoices', only: [:index, :new, :edit] do
  collection do
    get :search
    post :search
  end
end

这将产生以下路线:

search_deliveries  GET  /deliveries/search(.:format)    invoices#search
                   POST /deliveries/search(.:format)    invoices#search
        deliveries GET  /deliveries(.:format)           invoices#index
      new_delivery GET  /deliveries/new(.:format)       invoices#new
     edit_delivery GET  /deliveries/:id/edit(.:format)  invoices#edit

答案 1 :(得分:1)

resources :invoices, path: 'deliveries' do
 collection do
  match 'search' => 'invoices#search', via: [:get, :post], as: :search
 end
end

它将生成前缀为/deliveries/your_action

的路由