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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With