Rails移除控制器路径从URL中

3
我在我的视图中有以下循环:
<% @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
2个回答

9
您可以这样做:
#config/routes.rb
resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show

--
另外,请确保将此放在路由的底部;因为它将覆盖先前的所有路由。例如,domain.com/users 将重定向到 posts 路径,除非在 routes.rb 文件的底部定义了 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

好的 - 我正在为您更新关于slug的信息 - Richard Peck
1
当然,我正在使用友好的ID,但对于链接resources :posts, path: "",这是唯一的方法,对吗? - Prabhakaran
是的,除非您以编程方式输出页面或其他操作。 - Richard Peck

-1

你需要告诉路由路径的名称。

在routes.rb文件中,你可以这样做:

get '/:id', constraints: { the_id: /[a-z0-9]{6}\-[a-z0-9]{6}/ }, to: 'posts#show', as: :custom_name

之后当你运行 'rake routes' 时,你会看到:

Prefix Verb   URI Pattern                Controller#Action
custom_name GET    /:id(.:format)         post#show {:id=>/[a-z0-9]{6}\-[a-z0-9]{6}/}

现在您已经有了前缀动词,可以使用它来生成链接: <%= link_to '显示', custom_name_path( post.id ) do %> 一些 HTML <% end %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接