【问题标题】:rails remove controller path from the urlrails 从 url 中删除控制器路径
【发布时间】:2014-06-30 18:32:27
【问题描述】:

我认为有以下循环

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-routing


    【解决方案1】:

    你可以这样做:

    #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
    

    【讨论】:

    • 很好 - 我正在为你更新关于蛞蝓的信息
    • 当然我使用的是友好的 id 但对于链接 resources :posts, path: "" 这是唯一的方法吗?
    • 是的,除非您以编程方式或其他方式输出页面
    【解决方案2】:

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

    在 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}/}
    

    现在您有了前缀动词,您可以使用它来生成链接: 一些html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2017-01-14
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      相关资源
      最近更新 更多