这是我的link_to
<%= link_to sub_category.name, controller: :posts, action: :product, id: "#{sub_category.slug}-#{sub_category.id}" %>
指向网址
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 :(得分:0)
如果您希望路径/:id
与您的posts#product
匹配,那么您的路线中应该有类似的内容:
resources :posts
match ':id', to: 'posts#product`, via: :get
match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
答案 1 :(得分:0)
@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}" %>