Rails自定义路由变得困惑:id

Rah*_*hul 0 ruby-on-rails

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

route.rb

  controller 'beverage_locations' do
     get 'beverage_locations/:location_id' => 'beverage_locations#index'
     get 'beverage_locations/new' => 'beverage_locations#new'
  end
Run Code Online (Sandbox Code Playgroud)

错误

ActiveRecord::RecordNotFound in BeverageLocationsController#index

Couldn't find Location with id=new
Run Code Online (Sandbox Code Playgroud)

任何想法如何解决这个问题?

谢谢!

zho*_*uoa 6

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

来自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
Run Code Online (Sandbox Code Playgroud)