如何从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] 
+0

,请复制粘贴你的config/routes.rb文件的内容。 –

+0

@MarekLipka包括我的'route.rb'你可以请检查。 – overflow

什么@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}" %> 
+0

'/ pp'是什么意思,以及如何在link_to – overflow

+0

中使用它@Seting更新了答案,你是什么意思的“但网址为我的旧网址”? – tihom

+0

对不起,输错了。现在链接指向'localhost:3000/somethins-test-1',但在点击链接时出现'路由错误' – overflow

如果你想路径/:id符合您posts#product,你应该在你的路线是这样的:

resources :posts 
match ':id', to: 'posts#product`, via: :get 
match ':controller(/:action(/:id))(.:format)', via: [:get, :post] 
+0

工作良好,但我需要澄清。如果我有'id' for'other_controller#other_action'会发生什么? – overflow

+0

@Seting':controller /:action /:id'将会生成URL。 –

+0

对不起,我不明白你能不能简单地告诉我 – overflow