1

我正在尝试设置自定义路线。但是,每当我点击 Drink_locations/new 页面时,它都会尝试在 url 中发送“new”作为索引路径中的 :location_id。

路由.rb

  controller 'beverage_locations' do
     get 'beverage_locations/:location_id' => 'beverage_locations#index'
     get 'beverage_locations/new' => 'beverage_locations#new'
  end

错误

ActiveRecord::RecordNotFound in BeverageLocationsController#index

Couldn't find Location with id=new

知道如何解决这个问题吗?

谢谢!

4

2 回答 2

8

Rails 路由按照指定的顺序进行匹配,因此如果您在 get 'photos/poll' 上方有一个资源 :photos,则资源行的 show action 路由将在 get 行之前匹配。要解决此问题,请将 get 行移到资源行上方,以便首先匹配。

来自http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

一个演示:

# beverage_locations_controller.rb
class BeverageLocationsController < ApplicationController
  def index
    render :text => params[:location_id]
  end

  def new
    render :text => 'New method'
  end
end

# config/routes.rb
Forfun::Application.routes.draw do
  controller 'beverage_locations' do
     get 'beverage_locations/new'          => 'beverage_locations#new'
     get 'beverage_locations/:location_id' => 'beverage_locations#index'
  end
end
# http://localhost:3000/beverage_locations/1234   =>  1234
# http://localhost:3000/beverage_locations/new    =>  New method
于 2013-05-13T16:25:16.800 回答
2

您需要交换路线的顺序,以便new操作具有优先权:

controller 'beverage_locations' do
   get 'beverage_locations/new' => 'beverage_locations#new'
   get 'beverage_locations/:location_id' => 'beverage_locations#index'
end
于 2013-05-13T16:24:17.377 回答