Home > Software design >  Ruby on Rails routes - Query parameter vs id
Ruby on Rails routes - Query parameter vs id

Time:05-01

I'm trying to set a route that accepts a dynamic field. Restaurants have categories [:chinese, :fast_food, :french, :vegan] and the route restaurants/vegan allows, in the index action, to return a list of the restaurants under this category (the request is only /restaurants then it returns all restaurants) and this is working.

But then the show action is not working because it gets stuck in the index action. "restaurant/2" doesn't work because the index action looks for a category of 2 and 2 is the restaurant.id

Is there any way to distinguish both dynamic fields?

Thanks in advance

routes.rb

  get "restaurants/:category", to: "restaurants#index"
  resources :restaurants, only: [:index, :show, :new, :create, :destroy]

restaurants_controller

def index
    raise
    if params[:category]
      @restaurants = Restaurant.where(categories: params[:category])
    else
       @restaurants = Restaurant.all
    end
end

def show
 @restaurant = Restaurant.find(params[:id])
end

CodePudding user response:

Because you have a dynamic segment in the same position as :id you have to use constraints on your route.

https://guides.rubyonrails.org/routing.html#segment-constraints


# `restaurants/1` will be ignored
# `restaurants/anything-else` will be routed to RestaurantsController#index
get 'restaurants/:category',
   to: 'restaurants#index',
   constraints: { category: /[^0-9] / }

resources :restaurants
  • Related