Rahul
Rahul

Reputation: 464

Rails Custom Route Gets Confused on :id

I am trying to setup a custom route. However whenever I hit the beverage_locations/new page, it tries to send 'new' in the url as the :location_id in the index path.

route.rb

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

error

ActiveRecord::RecordNotFound in BeverageLocationsController#index

Couldn't find Location with id=new

any idea how to fix this?

Thanks!

Upvotes: 1

Views: 647

Answers (2)

zhongguoa
zhongguoa

Reputation: 336

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action’s route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

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

A demo:

# 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

Upvotes: 8

alf
alf

Reputation: 18530

You need to swap the order of the routes so that the new action has preference:

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

Upvotes: 3

Related Questions