Итак, у меня есть веб-приложение, которое позволяет двум пользователям отправлять сообщения друг другу.«Получатель» и «отправитель».Когда два пользователя впервые пытаются отправить сообщение друг другу, это прекрасно работает.Но если пользователь пытается отправить сообщение другому человеку, Action Cable не создает новый разговор и возвращает его к разговору, который он имел с первым человеком.Это происходит потому, что мой "if Conversation.between" возвращает true, когда должен возвращать FALSE!У меня есть скриншот ниже: (игнорируйте '&', который был вставлен только для того, чтобы получить ошибку)
Изображение разговор. Между возвратом истины, когда должно быть ЛОЖЬ:
![enter image description here](https://i.stack.imgur.com/Dv5Lh.png)
В любом случае, мой код приведен ниже, и если кто-то может решить эту головную боль, с которой я имел дело, был бы очень признателен.спасибо
Контроллер бесед:
class ConversationsController < ApplicationController
before_action :authenticate_user!
def index
@conversations = Conversation.involving(current_user)
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 MessagesController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation
def index
if current_user == @conversation.sender || current_user == @conversation.recipient
@other = current_user == @conversation.sender ? @conversation.recipient : @conversation.sender
@messages = @conversation.messages.order("created_at DESC")
else
redirect_to conversations_path, alert: "You don't have permission to view this."
end
end
def create
@message = @conversation.messages.new(message_params)
@messages = @conversation.messages.order("created_at DESC")
if @message.save
ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
redirect_to conversation_messages_path(@conversation)
end
end
private
def render_message(message)
self.render(partial: 'messages/message', locals: {message: message})
end
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
end
def message_params
params.require(:message).permit(:conteny, :user_id)
end
end
Модель разговора:
class Conversation < ApplicationRecord
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, :recipient_id
scope :involving, -> (user) {
where("conversations.sender_id = ? OR conversations.recipient_id = ?", user.id, user.id)
}
scope :between, -> (user_A, user_B) {
where("(conversations.sender_id = ? OR conversations.recipient_id = ?) OR conversations.sender_id = ? OR conversations.recipient_id = ?", user_A, user_B, user_B, user_A)
}
end
Модель сообщения:
class Message < ApplicationRecord
belongs_to :user
belongs_to :conversation
validates_presence_of :content, :conversation_id, :user_id
after_create_commit :create_notification
def message_time
self.created_at.strftime('%B %d, %Y')
end
private
def create_notification
if self.conversation.sender_id == self.user_id
sender = User.find(self.conversation.sender_id)
Notification.create(content: "New message from #{sender.fullname}", user_id: self.conversation.recipient_id)
else
sender = User.find(self.conversation.recipient_id)
Notification.create(content: "New message from #{sender.fullname}", user_id: self.conversation.sender_id)
end
end
end
Пожалуйста, помогите, я боролся около недели.спасибо.