First, since you want to look up Movie
by "slug" like the-social-network
, you need to extend FriendlyId
and tell it to parameterize the id
into an attribute called slug
. Do this by passing :slugged
as follows:
# app/models/movie.rb
class Movie < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
end
Then, create a migration to store slug
for Movie
objects:
# in console
rails g migration add_slug_to_movies slug:string
Modify the migration file to add slug
as an index:
# change migration file
class AddSlugToMovies < ActiveRecord::Migration
def change
add_column :movies, :slug, :string
add_index :movies, :slug
end
end
Finally, you need to create a slug for all the existing movies in your database. You can do this by saving each movie one-by-one:
# in Rails console
Movie.find_each(&:save)
After you'd done this, you should be able to make lookups on Movie
akin to /movies/the-social-network/comments/new
.
Check out this Railscast for additional details and examples, including ensuring that an object's slug is correctly update when the title is changed in the database.