如何从Rails应用中移除控制器路径而不影响网址结构?

更新于
2026-10-09 20:25:06
3阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计340个文字,预计阅读时间需要2分钟。

如何从Rails应用中移除控制器路径而不影响网址结构?

我理解您想要修改代码,使其生成的链接格式更符合您的需求。以下是修改后的代码:

ruby@posts.each do |post|=link_to post do Some endend

此代码段将生成链接为 `localhost:3000/posts/sdfsdf-sdfsdf`,而不是 `localhost:3000/posts/sdfsdf-sdfsdf`。

我认为我有以下循环

如何从Rails应用中移除控制器路径而不影响网址结构?

<% @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

本文共计340个文字,预计阅读时间需要2分钟。

如何从Rails应用中移除控制器路径而不影响网址结构?

我理解您想要修改代码,使其生成的链接格式更符合您的需求。以下是修改后的代码:

ruby@posts.each do |post|=link_to post do Some endend

此代码段将生成链接为 `localhost:3000/posts/sdfsdf-sdfsdf`,而不是 `localhost:3000/posts/sdfsdf-sdfsdf`。

我认为我有以下循环

如何从Rails应用中移除控制器路径而不影响网址结构?

<% @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