简体   繁体   中英

Ruby on Rails routes - Query parameter vs id

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM