Reputation: 73
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
Upvotes: 7
Views: 3536
Reputation: 1432
As of the latest version of the friendly_id
gem, you can say:
Book.friendly.exists? params[:book_id]
Upvotes: 18
Reputation: 747
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!
Upvotes: 2
Reputation: 2571
Rescue from RecordNotFound exception ==>
def book
@book = Book.find(params[:book_id])
#OK
rescue ActiveRecord::RecordNotFound => e
head :not_found
end
Upvotes: 5
Reputation: 83680
@book = Book.find_by_id(params[:book_id])
if @book
# OK
else
#404 not found
enв
Upvotes: -2