找不到Rails 4.0记录

时间:2013-07-12 20:45:27

标签: ruby-on-rails

在我的编辑操作中,如果记录不存在,我永远不会找到未找到的记录。我做错了什么。

这是我的编辑操作

    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 

对于nil,我总是得到未定义的方法`country':NilClass用于我的原始编辑记录。

另外,我提高了我的show动作中找不到的记录,但我想使用我公共文件夹中的404.html页面。我该如何使用这个文件???

提前致谢

1 个答案:

答案 0 :(得分:12)

问题在于,您的专线@offer = Offer.find_by(edit_hash: params[:edit_hash])没有回复ActiveRecord::RecordNotFound。它正在回复nil

您可以通过rails c打开应用程序目录中的Rails控制台来查看此信息。在控制台中,将其放入:

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

您会看到其输出为=> nil。然后,您可以输入@offer,然后再次看到它的输出为=> nil。现在,将此行放入控制台:

@offer = Offer.find(99999)

您会看到其输出为ActiveRecord::RecordNotFound: Couldn't find Offer with id=99999

要解决此问题,请在!来电中添加find_by,这样就可以了:

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

这会导致Rails回复ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound而不是nil

相关问题