Friendly ID - undefined method `slug=' for
Basic point is that, if you're using the friendly ID gem, then you will need to add a slug column, to the relevant ActiveModel table.
Example: Add a slug to my Project model
Each Project has a name (attribute).
class Project < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
validates :name, :state, presence: true
end
1. Run a migration to add a slug column
This can be done easily in rails:
rails g migration AddSlugToProjects slug
2. Don't forget the index!:
Make sure you add in an index on the slug column:
class AddSlugToProjects < ActiveRecord::Migration[5.2]
def change
add_column :projects, :slug, :string
add_index :projects, :slug
end
end
And now you're off to the races!
Richard Peck 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
Now, I have introduced Friendly ID without slug column
I don't know exactly what you mean here, but simply, it's like trying to start a car without the key
FriendlyID
The way FriendlyID works is to use a slug
(or other identifier) column to both create the slugged URL, and find based off the slugged ID:
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
This allows the gem to find based off either the id
or the slug
attribute
If you miss out the slug
column, this will prevent this from working, causing your error. The ways to fix this are:
- Use the slug column
- Create a slug attribute using
attr_accessor
If you'd like to try the second option, you could try this:
#app/models/ModelName.rb
attr_accessor :slug