2

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

错误是

未定义的方法“is_participant?” 对于零:NilClass


我肯定看到/usr/local/lib/ruby/gems/1.9.1/gems/mailboxer-0.7.0/app/models/conversation.rb中存在“is_participant”方法

消息控制器.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
4

3 回答 3

3

在调用它的方法之前,您需要检查它@conversation不是 nil。尝试

unless @conversation.present? && @conversation.is_participant?(current_user)
于 2012-07-06T06:13:40.377 回答
1

You can check for presence of a value or rescue for that error.

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

Notice that the rescue way is not very friendly, since it can rescue other error and making you have a pain to debug some errors. For example if current_user has no method named read, it would throw and error that would be catch there and you wouldn't notice it came from there.

于 2012-07-06T06:21:01.583 回答
1

Christoph Petschnig 的回答是正确的,只是想提一下有一个很好的速记

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

这是

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

try 将返回 nil is @conversation is nil 最终在 if 语句中计算为 false。

于 2012-07-06T11:02:09.087 回答