ruby-on-railsfriendly-id

Prevent IDs with Record.friendly.find param


I'm using FriendlyId and Rails.

I would like to support finding by the slug: https://example.com/restaurants/plaza-diner

But NOT support finding by its ID: https://example.com/restaurants/23

I'm using Restaurant.friendly.find(params[:id]) which by default does support both. How can I make it so retrieving by IDs is not supported?

Using find_by(slug: params[:id]) is not an option, as it skips FriendlyId's internals and does not support historical slugs for example.

I could check to see if params[:id] is an integer and raise a ActiveRecord:RecordNotFound, but that seems convoluted. Is there a simpler approach?

Relevant file: https://github.com/norman/friendly_id/blob/819c0b111b0f722809c0a13ad025c5191a278f85/lib/friendly_id/finders.rb


Solution

  • Use Restaurant.friendly.find_by_friendly_id(params[:id]).

    Finds exclusively by the friendly id, completely bypassing original find.

    See: