ruby-on-rails - 如何避免 nil 对象的错误

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

记录 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/

相关文章:

python - 无法将 Pandas 数据框保存到csv

ruby-on-rails - Rails + AngularJs 网络应用程序

ruby-on-rails - Rails从before_filter方法中设置布局

ruby-on-rails - Rails - 无法访问 Controller 中的参数

ruby-on-rails - 带有内联附件的 Rails 邮件程序错误

ruby-on-rails - Ruby on Rails - 路由错误,转到 "show"而不是 "index"

ruby-on-rails - rails : render a collection of models using an specific html view

ruby - 在 Shopify Ruby 中使用 "contain"运算符来处理 cart.discount_code - 不起作用

python - 捕获数据库错误的有效方法

python - 当不同的应用程序访问它时维护 mysql 中的数据完整性