如何将网址中的ruby-on-rails – rails控制器路径改写成长尾词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计444个文字,预计阅读时间需要2分钟。
我理解您想要修改代码,使其生成的链接格式从 `localhost:3000/posts/sdfsdf-sdfsdf` 变为 `localhost:3000/sdfsdf-sdfsdf`。以下是修改后的代码:
ruby@posts.each do |post|=link_to post do Some endend
这段代码中,`link_to` 方法生成的链接默认包含了 `/posts/` 前缀。为了去除这个前缀,您需要在 `link_to` 方法中指定路径时,直接写上您想要的链接部分,如下所示:
ruby@posts.each do |post|=link_to post, /#{post.path} do Some endend
这里假设 `post.path` 是您想要链接的部分,例如 `sdfsdf-sdfsdf`。这样修改后,每个链接将只包含 `/sdfsdf-sdfsdf`,而不包含 `/posts/`。
<% @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 你可以这样做:
#config/routes.rb resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show
–
另外,请确保将其放在路线的底部;因为它会覆盖任何前面的路线.例如,domain.com/users将重定向到posts路径,除非posts路径定义在routes.rb文件的底部
–
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
本文共计444个文字,预计阅读时间需要2分钟。
我理解您想要修改代码,使其生成的链接格式从 `localhost:3000/posts/sdfsdf-sdfsdf` 变为 `localhost:3000/sdfsdf-sdfsdf`。以下是修改后的代码:
ruby@posts.each do |post|=link_to post do Some endend
这段代码中,`link_to` 方法生成的链接默认包含了 `/posts/` 前缀。为了去除这个前缀,您需要在 `link_to` 方法中指定路径时,直接写上您想要的链接部分,如下所示:
ruby@posts.each do |post|=link_to post, /#{post.path} do Some endend
这里假设 `post.path` 是您想要链接的部分,例如 `sdfsdf-sdfsdf`。这样修改后,每个链接将只包含 `/sdfsdf-sdfsdf`,而不包含 `/posts/`。
<% @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 你可以这样做:
#config/routes.rb resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show
–
另外,请确保将其放在路线的底部;因为它会覆盖任何前面的路线.例如,domain.com/users将重定向到posts路径,除非posts路径定义在routes.rb文件的底部
–
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

