4

I downloaded the friendly_id gem in order to make my URLs more user friendly. To honor their instructions, I am asking this here instead of on GitHub.

Here is my Show Method

def show
  @movie = Movie.friendly.find(params[:id])
end

This is in compliance with their documentation

Finders are no longer overridden by default. If you want to do friendly finds, you must
do Model.friendly.find rather than Model.find. You can however restore FriendlyId 
4-style finders by using the :finders addon:

In my Model.rb file, I have the following

extend FriendlyId
friendly_id :title, use: :slugged

From their documentation

friendly_id :foo, use: :slugged # you must do MyClass.friendly.find('bar')

also from their documentation

def set_restaurant
  @restaurant = Restaurant.friendly.find(params[:id])
end

For reference, here is their guide.

Granted, I haven't generated a migration yet, because I had already created the table.

I'm unsure of what my next step should be?

Thank you for your help.

Johnson
  • 1,679
  • 1
  • 14
  • 21

3 Answers3

16

You need to run a migration to add the slug column to your table:

class AddSlugToMovies < ActiveRecord::Migration
  def change
    add_column :movies, :slug, :string, unique: true
  end
end

Run rake db:migrate, and then in your rails console run Move.find_each(&:save) to populate the slug column.

Marina
  • 3,222
  • 5
  • 25
  • 35
2

Marina is correct that you have to add slug field.

But lot's of people got confused because FriendlyID generates friendly_id_slugs table which contains sluggable_id and sluggable_type field.

create_table "friendly_id_slugs", force: :cascade do |t|
t.string   "slug",                      null: false
t.integer  "sluggable_id",              null: false
t.string   "sluggable_type", limit: 50
t.string   "scope"
t.datetime "created_at"
t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
t.index ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id"
t.index ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type"
end

Basically it generates friendly_id_slugs table for History Module. Have a look at their documentation about History__Avoiding_404_s_When_Slugs_Change : http://norman.github.io/friendly_id/file.Guide.html#History__Avoiding_404_s_When_Slugs_Change

Vaibhav
  • 858
  • 10
  • 13
0

If you are getting started with a new table you can also do this:

class CreateMovies < ActiveRecord::Migration
  def change
    create_table :movies do |t|
      ...
      t.string :slug
      t.index :slug, unique: true, using: :btree
    end
  end
end
Abram
  • 39,950
  • 26
  • 134
  • 184