Search code examples
ruby-on-railsrails-routing

Structure a valid route


I have the following routes inside my Rails.application.routes

get '/c/*name', :to => 'categories#show', :as => :filter_categories
get '/c/*name/*token', :to => 'categories#nest_products', :as => :nest_categories

and this controller

class CategoriesController < ApplicationController
  def show
    params[:name]
    @products, @filters = ProductFilterService.new(params[:name]).filter_by_taxon
    @selected_taxons = ProductFilterService.new(params[:name]).selected_taxons
  end

  def nest_products
    puts params[:token]
    render :show
  end
end

trying like this example localhost:3000/adidas/fH72VLNlAma2JWc, i want to excecute the method nest_products but always goes to method show.


Solution

  • Just change the declaration order of your routes like this, so it matches nest_categories first if you have a token param :

    get '/c/*name/*token', :to => 'categories#nest_products', :as => :nest_categories
    get '/c/*name', :to => 'categories#show', :as => :filter_categories
    

    Because localhost:3000/adidas/fH72VLNlAma2JWc matches both routes, you need to declare the most specific first.