Friendly Id

Friendly ID is the most popular ruby gem for making friendly urls in Rails.
Icons/chart bar
Used 142 times
Created by
A Andrea Fomera

Usage
To use this template, run the command below; 

If you have an existing model while it runs enter 'yes' when it prompts you if you want to add it to an existing model, then fill in the model name, for example Post or User. We'll generate a migration to add the Slug column and then add the code to the model for you.

If you don't have any existing models, remember to generate your models when you do with a slug:uniq attribute. It will default to a string field in the database.

Then all you need to do is use Friendly ID's friendly find scope in your controllers:

# Previously:
@post = Post.find(params[:id])

# After, with friendly ID
@post = Post.friendly.find(params[:id])


Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/VqqsgV"
Template Source

Review the code before running this template on your machine.

def ask_with_default(prompt, default)
  value = ask("#{prompt} (default: #{default})")
  value.present? ? value : default
end

run "bundle add 'friendly_id'"

rails_command "generate friendly_id"

while yes?("Do you want to use Friendly ID with an existing model?") do
  model_name = ask_with_default("Model Name:", "Post")
  attribute = ask_with_default("Attribute:", "name")
  if model_name && attribute
    # We generate a migration to add the friendly id slug column.
    generate(:migration, "AddSlugTo#{model_name.titleize.pluralize}", "slug:uniq")
    string = <<~RUBY
          extend FriendlyId
          friendly_id :#{attribute}, use: :slugged
    RUBY
    # Inject the friendly id methods into the class.
    inject_into_file "app/models/#{model_name.downcase}.rb", string, after: "class #{model_name.titleize} < ApplicationRecord\n"
  end
end

# Run migrations for newly generated migrations
rails_command "db:migrate"

puts "👋 Remember to change any `find` calls and follow the usage instructions: https://railsbytes.com/public/templates/VqqsgV"
Comments
Chris Oliver
Friendliest IDs in the land!