Rails Quickstart
suggest changerails new my_app
cd my_app
Gemfile
FriendlyId 5.0 or newer is required for Rails 4.0+. '~> 5.1.0' means >= 5.1.0 and < 5.2.0.
gem "friendly_id", "~> 5.1.0"
rails generate friendly_id
rails generate scaffold user name:string slug:string:uniq
rails db:migrate
edit app/models/user.rb
class User < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
end
User.create! name: "Joe Schmoe"
In the controller, use friendly.find. User.find still looks up the numeric id.
User.friendly.find(params[:id])
Run the server
rails server
Open http://localhost:3000/users/joe-schmoe.
Existing records
If you add FriendlyId to an existing app, generate slugs from the console, a runner, or a Rake task:
User.find_each(&:save)
Finders are no longer overridden by default. Use Model.friendly.find, not Model.find, unless you add the :finders addon.
friendly_id :foo, use: :slugged # MyClass.friendly.find("bar")
# or
friendly_id :foo, use: [:slugged, :finders] # MyClass.find("bar")
A new “candidates” functionality which makes it easy to set up a list of alternate slugs that can be used to uniquely distinguish records, rather than appending a sequence. For example:
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
Limit the slug length by overriding normalize_friendly_id. super[0..40] keeps 41 characters.
def normalize_friendly_id(string)
super[0..40]
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents