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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With