我正在嘗試設定一個接受動態欄位的路由。餐廳有類別 [:chinese, :fast_food, :french, :vegan] 并且路線restaurants/vegan 允許在索引操作中回傳此類別下的餐廳串列(請求僅為/restaurants 然后它回傳所有餐廳),這是有效的。
但是隨后顯示操作不起作用,因為它卡在索引操作中。“restaurant/2”不起作用,因為索引操作查找類別 2,而 2 是 restaurant.id
有沒有辦法區分這兩個動態欄位?
提前致謝
路線:
獲取“restaurants/:category”,到:“restaurants#index”資源:restaurants,僅:[:index, :show, :new, :create, :destroy]
控制器:
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
uj5u.com熱心網友回復:
因為您在同一位置有一個動態段,因為: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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468137.html
