我遵循教程,允許用戶在我的應用上發送其他消息。我正在使用設計進行身份驗證。基本上,如果兩個或兩個以上用戶之間有對話,並且一個或多個用戶取消了他們的帳戶,則剩下的用戶將無法再訪問索引頁進行對話。我在ConversationsController#index
得到ActiveRecord::RecordNotFound
。如果用戶之間有消息並且用戶刪除了他的帳戶,另一個用戶將無法再訪問Rails中的消息索引。
粗體代碼是錯誤被識別的地方。解決這個問題的最好方法是什麼?
在此先感謝
索引視圖:
<% @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