What are the best practices for generating SEO friendly urls in Rails 5?
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
For generating SEO-friendly URLs in Rails 5, a good approach is to use the to_param
method to customize the URL structure. This allows you to replace numeric IDs like articles/2
with something more descriptive, such as articles/article-heading
. I've also used the FriendlyId gem, which is great for creating human-readable slugs for your records. It makes URLs more SEO-friendly by turning them into something both user- and search-engine-friendly. Worth checking out if you haven't already!
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.
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?
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.
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.