Friendly Id

forked from Friendly Id

FriendlyId is the "Swiss Army bulldozer" of slugging and permalink plugins for Active Record. It lets you create pretty URLs and work with human-friendly strings as if they were numeric ids.
url 1,036 1


Dave Kimura
Dave Kimura

May 11, 2020

Copy and paste this code into your terminal

DISCLAIMER: You should always review templates before running them. By running the template, you are agreeing to the terms of use.

The contents of this script as show. Any updates will be reflected in the below code and the snippet.

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

gem 'friendly_id'
run 'bundle install'

while yes?("Do you want to use Friendly ID with a model?") do
  model_name = ask_with_default("Model Name:", "user")
  attribute_name = ask_with_default("Attribute Name:", "name")
  if model_name && attribute_name
    generate(:migration, "AddSlugTo#{model_name.titleize.pluralize}", "slug:uniq")
    string = <<~RUBY
          extend FriendlyId
          friendly_id :#{attribute_name}, use: :slugged
    RUBY
    inject_into_file "app/models/#{model_name}.rb", string, after: "class #{model_name.titleize} < ApplicationRecord\n"
  else
    puts "Model name and attribute required"
  end
end

generate(:friendly_id)

puts "Change references. I.e., User.find() to User.friendly.find()"

A place where you can thank the author, post problems, give constructive feedback, etc. Be nice!