加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – rails从网址中删除控制器路径

发布时间:2020-12-17 01:33:42 所属栏目:百科 来源:网络整理
导读:我认为我有以下循环 % @posts.each do |post| % %= link_to post do % Some html % end %% end % 上面的代码将生成链接为localhost:3000 / posts / sdfsdf-sdfsdf 但我想将链接作为localhost:3000 / sdfsdf-sdfsdf 这是我的路线 resources :posts,except:
我认为我有以下循环

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读