- Add the gem to your gemfile.
gem friendly_id
- After including FriendlyId, run the bundle command.
bundle install
- In order to add FriendlyId to an existing application, we will need to create a migration to add the necessary field to the model we want to use FriendlyId with. We add
uniq
to enforce unique slug values.rails g migration AddSlugToPost slug:uniq
- Now we need to update our database:
rake db:migrate
- Now, we need to add code to our model to tell rails that we wish to use FriendlyId. Open the desired model and add the following code.
extend FriendlyId
friendly_id :title, use: :slugged
- We are almost there! While technically we are all set up and good to go, existing data still doesn't have a slug. In order to add a slug, start a rails console:
rails c
- Inside the rails console, run a command to loop through each model and save it:
Posts.find_each(&:save)
- As a final step, we need to change our
.find
s to friendly finds.Post.find(params[:id])
becomesPost.friendly.find(params[:id])
- Now it should work! Checkout out dem purrty URLs.