在我看来,我有以下循环
<% @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 endI have the following loop in my view
<% @posts.each do |post| %> <%= link_to post do %> Some html <% end %> <% end %>The above code will generate link as localhost:3000/posts/sdfsdf-sdfsdf
But I would like to have the link as localhost:3000/sdfsdf-sdfsdf
Here is my route
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-
另外,确保你把它放在你的路线的底部 ; 因为它会覆盖任何前面的路线。 例如,除非posts路径在routes.rb文件的底部定义,否则domain.com/users将重定向到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 endYou could do this:
#config/routes.rb resources :posts, path: "" #-> domain.com/this-path-goes-to-posts-show--
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
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] endThis 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更多推荐
发布评论