Search code examples
ruby-on-railsfriendly-id

Avoid RecordNotFound exception with friendly_id gem


Is there a way to have friendly.find simply return nil when the slug isn't available in any record, rather than raise the ActiveRecord::RecordNotFound exception?


Solution

  • Looking at the source code for the friendly_id finders it doesn't appear to be configurable.

    def find_by_friendly_id(id)
      first_by_friendly_id(id) or raise raise_not_found_exception(id)
    end
    

    You can always do basic Rails lookup with

    Model.find_by(slug: 'some-nice-slug')