Hassen
Hassen

Reputation: 7654

Rails: Override 'Couldn't find Item with id=xxx' error to display flash error message

In my program, I have to get product info using the product id, like this:

# Show the product info.
def show
    @product = Product.find params[:id]

    if !@product
        redirect_to products_path, :alert => 'Product not found!.'
    end
end

In case the product doesn't exist, I have a Rails error Couldn't find Product with id=xxx. I would like to override this error message and display the error by myself as a flash alert.

How can I do that? Thanks in advance.

Upvotes: 1

Views: 2098

Answers (4)

Haris Krajina
Haris Krajina

Reputation: 15286

def show
    begin
      @product = Product.find params[:id]
    rescue ActiveRecord::RecordNotFound => e
      redirect_to products_path, :alert => 'Product not found!.'
    end
end

Always try to rescue specific exception, this would give you desired result. As @Emrah mentioned find method will raise ActiveRecord::RecordNotFound when there is no record with given id.

Upvotes: 1

emrahbasman
emrahbasman

Reputation: 2013

find method always raises ResourceNotFound. If you want custom error message only for this action, you can do like that:

def show
    @product = Product.find_by_id params[:id]

    if @product.blank?
        redirect_to products_path, :alert => 'Product not found!.'
    end
end 

Upvotes: 1

Christoph Petschnig
Christoph Petschnig

Reputation: 4157

The find method is specified to raise an error if nothing was found. You can use ARel style

@product = Product.where(:id => params[:id]).first

instead, which will return nil on an empty result.

Upvotes: 0

davidrac
davidrac

Reputation: 10738

You can write Product.try(:find, params[:id]) or Product.find_by_id params[:id] and get nil in case the product is not found instead of an exception

Upvotes: 4

Related Questions