チュートリアルに続いて、ユーザーは私のアプリケーションでメッセージを送信できます。私は認証のためにdeviseを使用しています。基本的に、2人以上のユーザーが会話を持ち、1人以上がアカウントをキャンセルすると、残りのユーザーは会話のインデックスページにアクセスできなくなります。私はActiveRecord::RecordNotFound
をConversationsController#index
に入れます。ユーザー間にメッセージがあり、ユーザーが自分のアカウントを削除した場合、もう1人のユーザーはRailsのメッセージインデックスにアクセスできなくなります。
太字のコードは、エラーが特定された場所です。これを解決する最良の方法は何でしょうか?事前に
おかげ
Indexビュー:
<% @conversations.each do |conversation| %>
<% if conversation.sender_id == current_user.id || conversation.recipient_id == current_user.id %>
<% if conversation.sender_id == current_user.id %>
**<% recipient = User.find(conversation.recipient_id) %>**
<% else %>
<% recipient = User.find(conversation.sender_id) %>
<% end %>
<tr>
<td><%= link_to (image_tag recipient.avatar.url, size: "50x50"), user_path(recipient) %></td>
<td><%= recipient.full_name %></td>
<td><%= link_to "View Message", conversation_messages_path(conversation) %></td>
</tr>
<% end %>
<% end%>
コントローラー:
class ConversationsController < ApplicationController
def index
@users = User.all
@conversations = Conversation.all
end
def create
if Conversation.between(params[:sender_id],params[:recipient_id])
.present?
@conversation = Conversation.between(params[:sender_id],
params[:recipient_id]).first
else
@conversation = Conversation.create!(conversation_params)
end
redirect_to conversation_messages_path(@conversation)
end
private
def conversation_params
params.permit(:sender_id, :recipient_id)
end
end
モデル:
class Conversation < ActiveRecord::Base
belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'
has_many :messages, dependent: :destroy
validates_uniqueness_of :sender_id, :scope => :recipient_id
scope :between, -> (sender_id,recipient_id) do
where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)
end
end
に
を変更。インデックスビュー自体を投稿しても、エラーの原因を特定するのに役立つわけではありません。 – angkiki