2

レコードID116は存在しないため、@conversationにnilを返す必要があります。
nilになったときにリダイレクトさせようとしましたが、example.com / messages / show?id=116にアクセスするとエラーが表示されます。

エラーは

未定義のメソッド`is_participant? ' nilの場合:NilClass


/usr/local/lib/ruby/gems/1.9.1/gems/mailboxer-0.7.0/app/models/conversation.rbに「is_participant」メソッドが存在することは間違いありません。

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
4

3 に答える 3

3

@conversationメソッドを呼び出す前に、それがnilでないことを確認する必要があります。試す

unless @conversation.present? && @conversation.is_participant?(current_user)
于 2012-07-06T06:13:40.377 に答える
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という名前のメソッドがない場合、そこでキャッチされるエラーがスローされ、そこから来たことに気付かないでしょう。

于 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を返します。@conversationis nilは、最終的にifステートメントでfalseと評価されます。

于 2012-07-06T11:02:09.087 に答える