Search code examples
ruby-on-railsduplicatesslug

Rails how to use 2 of the same slugs


I am using slugs in my project to give my params an other name but I have two params called: "how-does-it-work". (.../investor/how-does-it-work) (.../customer/how-does-it-work) I would like to use the slugs as how they are currently set. Is there a way to do that?


Solution

  • Create two distinct routes/controllers, and simply query the corresponding ActiveRecord model in the show action. Assuming there is a slug field on your models:

    Rails.application.routes.draw do
      resources :customers
      resources :investors
    end
    
    class CustomersController < ApplicationController
      def show
        @customer = Customer.find_by(slug: params[:id])
      end
    end
    
    class InvestorsController < ApplicationController
      def show
        @investor= Investor.find_by(slug: params[:id])
      end
    end
    

    This is probably the most conventional way to solve this problem in Rails. If you are using the friendly_id gem, the same approach more or less applies, except for maybe the query itself.

    Hope this helps.