Ask A Question

Notifications

You’re not receiving notifications from this thread.

What are the best practices for generating SEO friendly urls in Rails 5?

William Kennedy asked in Rails

What is the best way to generate SEO friendly urls?

The Rails default is to put the id in the URL e.g articles/2

I want to be able to have a url like this

articles/article-heading

Previously I have used the to_param method to generate a custom url as well as a gem called Friendly_id

I am just wondering if anyone has any other suggesstions on best practices

Reply

I'd recommend friendly_id. You don't have to override to_param with it and you can simply define the attributes you want as candidates for the ID in case there's some conflicts:

class Restaurant < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  # Try building a slug based on the following fields in
  # increasing order of specificity.
  def slug_candidates
    [
      :name,
      [:name, :city],
      [:name, :street, :city],
      [:name, :street_number, :street, :city]
    ]
  end
end

I've used friendly_id for years and it hasn't let me down once. It's what I'm using on GoRails as well for the forum urls too.

Reply

Perfect. I will stick with friendly id. Another question just to follow on from that. What about hiding the id in forms.

In this case the the id attribute has the id of the order. I am looking at gem called obfuscate id but it seems deprecated. This is a Rails 5 app.

What would be the best practice in this case?

Reply

Hmm, my main question is why do you want to hide the ID from the form?

Reply

For competitive reasons, if an orders id is present in the form via inspect element, the competitor is able to guess how many transactions have been done.

That is the main reason.

Reply

Makes sense. Well if you're using friendly_id, the only ID that users will see will be the slug, not the database ID. As long as you don't have a count as part of your slug you'll be fine. You can even have it generate a random string for the slug if you want.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.