ruby-on-railsrubygemsfriendly-id

How to raise an error on duplicate column slug in FriendlyId?


I use friendly_id gem and if my slug column have duplicate value, gem updates it by adding a unique key. I want raise error already been taken. How can i do this?


Solution

  • It seems friendly_id(v5.2.4) does not have an option to avoid setting the UUID when a slug conflict happens. So the best way to solve this it to redefine the method responsible for resolving the conflict and raise an exception.

    class Post < ApplicationRecord
      extend FriendlyId
      friendly_id :title, use: :slugged
    
      def resolve_friendly_id_conflict(candidates)
        raise ActiveRecord::RecordNotUnique
      end
    end