我有一个get请求,它看起来像这样,运行良好:
get ':slug', :to => "countries#show",
:constraints => lambda { |r|
Country.find_by_slug(r.params[:slug]).present? }, as: :country
这使得像site.com/japan
这样的url可以正常工作。
虽然这个结构看起来不太好,但我之所以使用它,是因为有很多遗留路由在根URL下打开。
不管怎样,
我需要在城市下部署额外的资源:
resources :places, only: :show
启用URL,如:site.com/japan/tv-tower
我试着用这样的东西:
constraints lambda { |request|
Country.find_by_slug(request.params[:slug]).present? } do
resources places, only: :show
end
但它不起作用。
我假设结果是没有japan/places/tv tower——如果你不设置路径,这就是你现在没有得到有效路线的原因。
我会忘记:鼻涕虫,只使用国家的资源,即使它只是表演,这将确保你仍然有一个有效的路线名称和路线,只针对没有列出地点的国家。
resources :countries, only: [:show], path: '', :constraints => proc { |req| Country.find_by_slug(req.params[:country_id].nil? ? req.params[:id] : req.params[:country_id]) } do
resources :places, path: ''
end
这会给你留下这样的路线:
country_places GET /:country_id(.:format) places#index
POST /:country_id(.:format) places#create
new_country_place GET /:country_id/new(.:format) places#new
edit_country_place GET /:country_id/:id/edit(.:format) places#edit
country_place GET /:country_id/:id(.:format) places#show
PATCH /:country_id/:id(.:format) places#update
PUT /:country_id/:id(.:format) places#update
DELETE /:country_id/:id(.:format) places#destroy
country GET /:id(.:format) countries#show