KK2
KK2

Reputation: 73

rails friendly_id and check if entry exists

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

Answers (4)

Hamed
Hamed

Reputation: 1432

As of the latest version of the friendly_id gem, you can say:

Book.friendly.exists? params[:book_id]

Upvotes: 18

icem
icem

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

Deepak N
Deepak N

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

fl00r
fl00r

Reputation: 83680

@book = Book.find_by_id(params[:book_id])
if @book
  # OK
else
  #404 not found
enв

Upvotes: -2

Related Questions