如何从URL中轨删除动作和控制器的link_to
问题描述:
这里是我的link_to
如何从URL中轨删除动作和控制器的link_to
<%= link_to sub_category.name, controller: :posts, action: :product, id: "#{sub_category.slug}-#{sub_category.id}" %>
这是指向URL
http://localhost:3000/posts/product/fifith-category-s-sub-category-2
我需要的网址如下
http://localhost:3000/fifith-category-s-sub-category-2
我该怎么做。
我route.rb
resources :posts
match ':controller(/:action(/:id))(.:format)', via: [:get,:post]
答
什么@MarekLipka建议是正确的,但你的定义这样的路线将占用您应用程序中的所有单层命名空间,即“/ anything”将默认路由到posts#product
。
我建议使用某种形式的标识符来确定哪些路由应该转到posts#product
。什么会为你工作取决于你为什么要这样做。选项夫妇是:
使用短命名空间:
scope '/pp' do
get ':id', to: 'posts#product
end
# "/pp/:id" routes to 'posts/product'
# pp is a random short name I picked, it could be anything
# link
<%= link_to sub_category.name, "pp/#{sub_category.slug}-#{sub_category.id}" %>
使用约束:
get ':id', to: 'posts#product`, constraints: { :id => /sub\-category/ }
# only id's with 'sub-cateogry' route to 'posts/product'
# link (assuming that sub_category.slug has 'sub-category' words in it)
<%= link_to sub_category.name, "#{sub_category.slug}-#{sub_category.id}" %>
答
如果你想路径/:id
符合您posts#product
,你应该在你的路线是这样的:
resources :posts
match ':id', to: 'posts#product`, via: :get
match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
,请复制粘贴你的config/routes.rb文件的内容。 –
@MarekLipka包括我的'route.rb'你可以请检查。 – overflow