rails从url中删除控制器路径(rails remove controller path from the url)

编程入门 行业动态 更新时间:2024-10-25 11:21:59
rails从url中删除控制器路径(rails remove controller path from the url)

在我看来,我有以下循环

<% @posts.each do |post| %> <%= link_to post do %> Some html <% end %> <% end %>

上面的代码将生成链接为localhost:3000/posts/sdfsdf-sdfsdf

但我希望链接为localhost:3000/sdfsdf-sdfsdf

这是我的路线

resources :posts, except: [:show] scope '/' do match ':id', to: 'posts#show', via: :get end

I have the following loop in my view

<% @posts.each do |post| %> <%= link_to post do %> Some html <% end %> <% end %>

The above code will generate link as localhost:3000/posts/sdfsdf-sdfsdf

But I would like to have the link as localhost:3000/sdfsdf-sdfsdf

Here is my route

resources :posts, except: [:show] scope '/' do match ':id', to: 'posts#show', via: :get end

最满意答案

你可以这样做:

#config/routes.rb resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show

-

另外,确保你把它放在你的路线的底部 ; 因为它会覆盖任何前面的路线。 例如,除非posts路径在routes.rb文件的底部定义,否则domain.com/users将重定向到posts路径

-

friendly_id

为了实现一个基于slug的路由系统(可以工作),你最适合使用friendly_id 。 这允许.find方法查找扩展模型的slug和id :

#app/models/post.rb Class Post < ActiveRecord::Base extend FriendlyID friendly_id :title, use: [:slugged, :finders] end

这将允许您在控制器中使用以下内容:

#app/controllers/posts_controller.rb Class PostsController < ApplicationController def show @post = Post.find params[:id] #-> this can be either ID or slug end end

You could do this:

#config/routes.rb resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show

--

Also, make sure you put this at the bottom of your routes; as it will override any preceding routes. For example, domain.com/users will redirect to the posts path unless the posts path is defined at the bottom of the routes.rb file

--

friendly_id

In order to achieve a slug-based routing system (which works), you'll be best suited to using friendly_id. This allows the .find method to look up slug as well as id for extended models:

#app/models/post.rb Class Post < ActiveRecord::Base extend FriendlyID friendly_id :title, use: [:slugged, :finders] end

This will allow you to use the following in your controller:

#app/controllers/posts_controller.rb Class PostsController < ApplicationController def show @post = Post.find params[:id] #-> this can be either ID or slug end end

更多推荐

本文发布于:2023-07-30 06:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   路径   url   rails   controller

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!