I have added the friendly_id
gem to my application. The name attribute is not replacing the index in the URL.
Gem
gem 'friendly_id', '~> 5.1.0'
Migration
rails g migration add_slug_to_items slug:string
Migration File
class AddSlugToItems < ActiveRecord::Migration
def change
add_column :items, :slug, :string
add_index :items, :slug
end
end
Controller
def show
@searched_item = Item.friendly.find(params[:id])
end
View-Path
/views/items/show.html.erb
Routes
resources :items, only: [:new, :create, :update, :show]
Button generating URL
<%= link_to fr.name, item_path(fr.id, search_info: params), class:"searched_kennel_title_link default_green_color" %>
Model
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
def should_generate_new_friendly_id?
name_changed?
end
This is a pre-existing application so I also ran:
Item.find_each(&:save)
The strange part is that when the URL is generated it is originally: http://localhost:3000/items/1
When I manually change the URL to: http://localhost:3000/items/item-name
it works.
Anyone have any idea why this would occur, or what I am missing?
2
Answers
Try using
You already have finders in your model.
On you view: Button generating URL
Did you try to replace
item_path(fr.id, search_info: params)
to:
item_path(fr, search_info: params)
or:
item_path(fr.slug, search_info: params)