I’m building a rails app that hosts games. Games belong to categories and thus each category can have many games.
I’m using the Friendly_id gem to generate URL slugs and have the following setup:
Category.rb
class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name_and_games, use: [:slugged]
has_many :games
def name_and_games
"#{name}-games"
end
end
Games_Controller.rb
...
def category
@category = Category.friendly.find(params[:id])
@categories = Category.all
@games = @category.games.page(params[:page])
render 'games/index'
end
...
Routes.rb
get ':friendly_id', to: "games#category", as: :category
Category_View.html.erb
<% categories.each do |category| %>
<%= link_to category_path(category) do %>
<span><%= pluralize(category.name.capitalize, "Game") %> (<%= category.games.count %>)</span>
<% end %>
<% end %>
The problem is that when I use Friendly_id’s slugged module, Rails is generating my urls WITHOUT the “-games” suffix so I end up with URLS like this:
http://localhost:3000/action
http://localhost:3000/adventure
Is there some way to have rails keep the “-games” in my URLs and have it all play nicely such that the “-games” are dropped when it comes time for processing in the model?
Thank you.
2
Answers
Turns out the issue wasn't that Friendly_id wouldn't make the update but that the slug was not getting refreshed.
I had to drop into the Rails console and manually set the "slug" column to nil for each category. Once I did this, Friendly_id reset the "slug" column to reflect my additional text.
So it’s: