Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.0 record not found

on my edit action I never rise the record not found if the record does not exist. What I'm doing wrong.

Here is my edit action

    class OffersController < ApplicationController

    rescue_from ActiveRecord::RecordNotFound, with: :record_not_found        

    def show
        @offer = Offer.find(params[:id])
    end        

    def edit
        @offer = Offer.find_by(edit_hash: params[:edit_hash])
        @country = Country.find_by(name: @offer.country)
        @states = State.find(:all, :conditions => { country_id: @country })
    end

    private

        def record_not_found
            render text: "404 Not Found", status: 404
        end
    end 

I always get undefined method `country' for nil:NilClass for my unexist edit record.

Also I raise the record not found on my show action, but I would like to use the 404.html page that I have on my public folder. How can I use this file???

Thanks in advance

like image 388
Jean Avatar asked Jul 12 '13 20:07

Jean


1 Answers

The problem is that your line @offer = Offer.find_by(edit_hash: params[:edit_hash]) is not responding with ActiveRecord::RecordNotFound. It's responding with nil.

You can see this by opening up your Rails console from your app's directory with rails c. In the console, put this in:

@offer = Offer.find_by(edit_hash: params[:edit_hash])

You'll see that its output is => nil. You can then type @offer and you'll see its output, again, is => nil. Now, put this line into the console:

@offer = Offer.find(99999)

You'll see that its output is ActiveRecord::RecordNotFound: Couldn't find Offer with id=99999.

To fix the problem, add a ! to your find_by calls, so they are like this:

@offer = Offer.find_by!(edit_hash: params[:edit_hash])

This will cause Rails to respond with ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound instead of nil.

like image 119
James Chevalier Avatar answered Oct 16 '22 00:10

James Chevalier