Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 845
KK2 Avatar asked Mar 13 '11 14:03

KK2


3 Answers

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

Book.friendly.exists? params[:book_id]
like image 129
Hamed Avatar answered Oct 15 '22 22:10

Hamed


Rescue from RecordNotFound exception ==>

def book
  @book = Book.find(params[:book_id])
  #OK
rescue ActiveRecord::RecordNotFound => e
  head :not_found
end
like image 26
Deepak N Avatar answered Oct 16 '22 00:10

Deepak N


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!

like image 2
icem Avatar answered Oct 16 '22 00:10

icem