Home > database >  ruby on raills routes query parameter vs id
ruby on raills routes query parameter vs id

Time:04-29

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 returna 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:

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

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