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
The above code will generate link as 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
文件
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
为了实现基于 slug 的路由系统(有效),您将最适合使用 friendly_id
.这允许 .find
方法为扩展模型查找 slug
和 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
这篇关于rails 从 url 中删除控制器路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!