如何避免nil对象的错误

时间:2012-07-06 05:55:58

标签: ruby-on-rails ruby-on-rails-3 error-handling controller null

记录ID 116不存在所以它应该返回nil到@conversation 当它变为nil时我试图使其重定向,但是当我访问example.com/messages/show?id=116时它仍然显示错误。

错误是

  

未定义的方法`is_participant?'为零:NilClass

我绝对看到了'is_participant'方法 /usr/local/lib/ruby/gems/1.9.1/gems/mailboxer-0.7.0/app/models/conversation.rb

messages_controller.rb

def show
  @conversation = Conversation.find_by_id(params[:id])

  unless @conversation.is_participant?(current_user)
    flash[:alert] = "You do not have permission to view that conversation."
    redirect_to :controller => 'messages', :action => 'received'
  end

  @messages = Message.find_by_id(params[:id])
  current_user.read(@conversation)    
end

3 个答案:

答案 0 :(得分:3)

在调用方法之前,您需要检查@conversation是否为零。尝试

unless @conversation.present? && @conversation.is_participant?(current_user)

答案 1 :(得分:1)

您可以检查是否存在值或该错误的救援。

def show
  @conversation = Conversation.find_by_id(params[:id])

  redirect_to somewhere_path if @conversation.nil?

  unless @conversation.is_participant?(current_user)
    flash[:alert] = "You do not have permission to view that conversation."
    redirect_to :controller => 'messages', :action => 'received'
  end

  @messages = Message.find_by_id(params[:id])
  current_user.read(@conversation)    
end

或救援!

def show
  @conversation = Conversation.find_by_id(params[:id])

  unless @conversation.is_participant?(current_user)
    flash[:alert] = "You do not have permission to view that conversation."
    redirect_to :controller => 'messages', :action => 'received'
  end

  @messages = Message.find_by_id(params[:id])
  current_user.read(@conversation)    

rescue NoMethodError
  redirect_to somewhere_path
end

请注意,救援方式不是很友好,因为它可以挽救其他错误并使您无法调试某些错误。例如,如果current_user没有名为read的方法,那么它会抛出并且会出现错误,并且你不会注意到它来自那里。

答案 2 :(得分:1)

Christoph Petschnig的答案是对的,只是想提一下

有一个很好的简写
unless @conversation.present? && @conversation.is_participant?(current_user)

unless @conversation.try(:is_participant? , current_user)

尝试将返回nil是@conversation是nil,最终在if语句中计算为false。