2

记录ID 116不存在,所以它应该返回nil给@conversation。
我试图让它在得到零时重定向,但是当我访问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

您需要检查@conversation你调用一个方法就可以了之前不为零。尝试

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

它工作完美,因为我想。谢谢! – MKK 2012-07-06 06:43:18

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 

or the rescue!

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的方法,它会抛出错误并且会在那里捕获,并且您不会注意到它来自那里。

1

克里斯托夫Petschnig答案是正确的,只是想更何况还有对

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

一个很好的速记是

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

尝试将返回nil是@Conversation是零,最终结果为false在if语句中。