norman / friendly_id

FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.
http://norman.github.io/friendly_id/
MIT License
6.15k stars 590 forks source link

Add `allow_nil: true` option to the finder #995

Closed joemsak closed 2 years ago

joemsak commented 2 years ago

This PR adds an optional allow_nil: true option to the finder

From discussion in #937 the idea is to add functionality that behaves like Rails' find_by which returns nil when a record is not found.

This is useful in conditions where the developer is allowing the primary key ID and the friendly slug ID but is not sure if the record will actually be found, and wants a nil instead of a raised exception.

Usage

MyModel.friendly.find("friendly-slug")
# => still works as expected, raises an ActiveRecord::RecordNotFound exception

MyModel.friendly.find("friendly-slug", allow_nil: true)
# => returns nil instead
parndt commented 2 years ago

Thanks, Joe! 🎉