Rails路由:GET方法重定向到show method

时间:2015-10-12 12:51:37

标签: ruby-on-rails ruby-on-rails-4 module routes

我有简单的控制器和路由文件。 在我的路线和控制器中,我创建了一个模块。我写了一个简单的方法,它重定向我的节目。我不知道为什么。

控制器

  module Seller
    class CampaignsController < Seller::BaseController

      before_action :confirm_logged_in

      def viewAllCampaigns
       @campaigns = Campaign.all

      end

      def show
      end

    end

  end

路由文件

 scope module: 'seller' do
   #namespace :power do
   resources :dashboard, only: [:index]
   resources :sessions, only: [:create, :destroy]
   resources :campaigns, only: [:index, :create, :show, :update, :destroy]   
   get 'viewAllCampaigns' => 'campaigns#viewAllCampaigns'   
 end

输出

Started GET "/campaigns/viewAllCampaigns" for 127.0.0.1 at 2015-10-12 17:39:43 +0500
  Processing by Seller::CampaignsController#show as HTML
  Parameters: {"id"=>"viewAllCampaigns"}
  Rendered seller/campaigns/show.html.erb (0.1ms)

我在浏览器中点击了http://localhost:3000/campaigns/viewAllCampaigns

3 个答案:

答案 0 :(得分:2)

理想情况下,您的routes应该像这样定义。

resources :campaigns, only: [:index, :create, :show, :update, :destroy] do  
   get 'viewAllCampaigns', on: :collection   
end

routes.rb文件的第一条评论为The priority is based upon order of creation: first created -> highest priority.这就是您的路由重定向到show的原因。 Rails将此网址视为campain/:id

答案 1 :(得分:1)

路线按顺序从上到下进行测试。您为show资源添加的campaigns路由将查找与此模式匹配的网址:

/campaigns/:id

/campaigns/viewAllCampaigns符合此标准,因此会执行show操作。params[:id] =&#34; viewAllCampaigns&#34;

将特殊情况路线向上移动到resources#campaigns路线上方以解决此问题,然后它将首先捕获网址。

get 'viewAllCampaigns' => 'campaigns#viewAllCampaigns'   
resources :campaigns, only: [:index, :create, :show, :update, :destroy]   

答案 2 :(得分:0)

它将以下get请求作为show动作,因为show需要campaign /:id,并且它假定'viewAllCampaigns'在此实例中是id:

/campaigns/viewAllCampaigns

您的link_to应该指向以下内容:

'/viewAllCampaigns'

您的路由结构并不是真正的RESTful,但这是一个单独的主题。

相关问题