Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails remove controller path from the url

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
like image 949
Prabhakaran Avatar asked Jun 28 '26 02:06

Prabhakaran


1 Answers

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
like image 121
Richard Peck Avatar answered Jun 30 '26 20:06

Richard Peck