[英]how to remove action and controller from url in rails link_to
Here is my link_to
这是我的
link_to
<%= link_to sub_category.name, controller: :posts, action: :product, id: "#{sub_category.slug}-#{sub_category.id}" %>
Which is pointing to the url 哪个指向URL
http://localhost:3000/posts/product/fifith-category-s-sub-category-2
I need the url as follows 我需要如下网址
http://localhost:3000/fifith-category-s-sub-category-2
How can i do it. 我该怎么做。
my route.rb 我的route.rb
resources :posts
match ':controller(/:action(/:id))(.:format)', via: [:get,:post]
If you want path /:id
match your posts#product
, you should have something like this in your routes: 如果您希望路径
/:id
与您的posts#product
匹配,则您的路线中应包含以下内容:
resources :posts
match ':id', to: 'posts#product`, via: :get
match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
what @MarekLipka suggests is correct but defining your routes like this will take up all the single level namespace in your app ie "/anything" will route by default to posts#product
. @MarekLipka的建议是正确的,但是像这样定义您的路由将占用您应用程序中的所有单级名称空间,即,“ / anything”将默认路由到
posts#product
。
I recommended using some form of identifier to figure out which routes should go to posts#product
. 我建议使用某种形式的标识符来确定应该去
posts#product
路线。 What will work for you depends on why you want to do this. 对您有用的取决于您为什么要这样做。 Couple of options are:
几个选项是:
Use a short namespace: 使用简短的名称空间:
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}" %>
Use a constraint: 使用约束:
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}" %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.