Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

ruby on rails - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

See:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...