Я использую Devise для аутентификации моего приложения, а затем я включил функцию чата (разговоры / сообщения) в свое приложение.Чат работает нормально, но как только я удалил пользователя, с которым общался, страница чата перестала работать, так как «Не удалось найти идентификатор пользователя = 1» (ошибка ActiveRecord)
my conversations controller
:
class ConversationsController < ApplicationController
before_action :authenticate_user!
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
мой mesages controller
:
class MessagesController < ApplicationController
before_action do
@conversation = Conversation.find(params[:conversation_id])
end
def index
@messages = @conversation.messages
@message = @conversation.messages.new
end
def new
@message = @conversation.messages.new
end
def create
@message = @conversation.messages.new(message_params)
if @message.save
redirect_to conversation_messages_path(@conversation)
end
end
private
def message_params
params.require(:message).permit(:body, :user_id)
end
end
мой conversation model
:
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
мой message model
:
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
validates_presence_of :body, :conversation_id, :user_id
def message_time
created_at.strftime("%m/%d/%y at %l:%M %p")
end
end
Iдобавил Разработать стандартный способ на основе документа, затем я добавил чат.
ОБНОВЛЕНИЕ:
Код сбой в этой строке: (views/conversations/index.html.erb
)
<% @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 %>
<h3><%= link_to recipient.email, conversation_messages_path(conversation)%></h3>
<% end %>
<% end %>
В частности, на <% recipient = User.find(conversation.sender_id) %>
О том, как работает функция удаления пользователя, я не кодировал это, я просто позволил Devise сделать свое дело