How to check if friendly_id entry exists before get it?
For example:
def book
@book = Book.find(params[:book_id])
end
It's ok, but i want check before if friendly_id exists, something like:
def book
if Book.exists?(params[:book_id])
@book = Book.find(params[:book_id])
else
#404 not found
end
As of the latest version of the friendly_id
gem, you can say:
Book.friendly.exists? params[:book_id]
Rescue from RecordNotFound exception ==>
def book
@book = Book.find(params[:book_id])
#OK
rescue ActiveRecord::RecordNotFound => e
head :not_found
end
I suggest you to move Deepak N's solution to model like I did:
def self.find_by_friendly_id(friendly_id)
find(friendly_id)
rescue ActiveRecord::RecordNotFound => e
nil
end
So now it will fetch your books by both id and slug and won't throw exception, just like standard AR method #find_by_id.
BTW, according the documentation #exists?
method now is right way to check record existance!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With