skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. So it’s:

    User.find_each{ |i| i.slug = nil; i.save!; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search