Ruby on Rails路由-查询参数vs id



我正在尝试设置一个接受动态字段的路由。餐馆有类别[:chinese, :fast_food, :french, :vegan],路由restaurants/vegan允许,在索引操作中,返回该类别下的餐馆列表(请求只有/restaurants,然后返回所有餐馆),这是工作的。

但是show动作不能工作,因为它卡在了index动作中。"restaurant/2"不起作用,因为索引动作查找类别2,而2是restaurant.id

是否有办法区分这两个动态字段?

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

因为你有一个与:id相同位置的动态段,你必须在你的路由上使用约束。

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

最新更新