记录 id 116 不存在,因此它应该返回 nil 给@conversation。
我试图让它在它为 nil 时重定向,但是当我访问 example.com/messages/show?id=116 时它仍然显示错误。
错误是
undefined method `is_participant?' for nil:NilClass
我肯定看到“is_participant”方法存在于
/usr/local/lib/ruby/gems/1.9.1/gems/mailboxer-0.7.0/app/models/conversation.rb
消息 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
最佳答案
在调用方法之前,您需要检查 @conversation
是否为 nil。尝试
unless @conversation.present? && @conversation.is_participant?(current_user)
关于ruby-on-rails - 如何避免 nil 对象的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11356603/