rails remove controller path from the url

2019-02-19 03:17发布

问题:

I 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

回答1:

You 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]
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


回答2:

you need to tell routes what the name of the path gonna be.

in routes.rb you can do something like:

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

after that when you run 'rake routes' you will see:

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

Now that you have the prefix verb, you can use it to generate the link: <%= link_to 'Show', custom_name_path( post.id ) do %> Some html <% end %>