Search code examples
ruby-on-railsrubyfriendly-id

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

Solution

  • Rescue from RecordNotFound exception ==>

    def book
      @book = Book.find(params[:book_id])
      #OK
    rescue ActiveRecord::RecordNotFound => e
      head :not_found
    end