如何绕过引发的异常(即使使用find_by_id)

时间:2013-10-18 01:41:22

标签: ruby-on-rails

正如标题所暗示的那样 - 即使我使用find_by_id,Heroku的制作也会引发异常。我不确定原因是什么,但是我使用begin/ensure来解决问题,但我仍然遇到了问题。

这是我最初的解决方案:

    def select_location
        begin
            region = Region.find_by_id(params[:Digits])
        ensure
            Twilio::TwiML::Response.new do |r|

                # if user pressed "9" (redirect)
                if (params[:Digits] == '0')

                    @response = r.Redirect call_hq_path, method: 'GET'

                # if region does not exist
                elsif !region.id
                    @response = r.Play Clip.where(name: "invalid").first.url
                    @response = r.Redirect index_path, method: 'GET'
                else
                    @response = r.Gather action: location_description_path(region), numDigits: '1' do |g|
                        region.locations.order(:number).each do |location|
                            g.Play location.listing_clip.url
                            g.Play number_url(location.number)
                        end
                        g.Play Clip.where(name: "9toreturn").first.url
                    end
                end
            end
        end

        render :xml => @response
    end

这里的问题出在elsif !region.id - 我仍然遇到这个错误:

2013-10-18T01:29:14.524289+00:00 app[web.1]: NoMethodError (undefined method `id' for nil:NilClass):

所以,我的两个问题:

  • begin/ensure是解决问题的最佳方法吗?
  • 如果是,我该如何解决elsif问题?

更新

.id删除elsif后,我收到此错误:

2013-10-18T02:06:57.055617+00:00 app[web.1]: NoMethodError (undefined method `url' for nil:NilClass):

elsif如何不解雇?

1 个答案:

答案 0 :(得分:0)

elsif !region.id不会检查区域是否存在,它会检查id对象的region属性是否返回nil。如果region不存在(因此为nil),则您实际上正在调用nil.id,这就是引发异常的原因。

如果您只是想检查region是否为nilelsif !region就足够了。

(根据你所拥有的内容,它看起来也不像begin / ensure块一样。)

相关问题