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

时间:2013-05-13 16:20:03

标签: 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

错误

ActiveRecord::RecordNotFound in BeverageLocationsController#index

Couldn't find Location with id=new

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

谢谢!

2 个答案:

答案 0 :(得分:5)

  

Rails路由按照指定的顺序进行匹配,所以如果你   有一个资源:上面的照片得到'照片/民意调查'的节目动作   资源行的路由将在获取行之前匹配。至   解决这个问题,将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

答案 1 :(得分:2)

您需要交换路线的顺序,以便new操作具有首选项:

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