【发布时间】:2019-05-26 00:45:39
【问题描述】:
当用户单击它时,我有一个名为对话的按钮,它会在数据库中创建对话作为记录。问题是如果有 3 个用户 userA、userB 和 userC,
如果用户B点击对话按钮向用户A发送消息,它将创建对话记录。但是如果用户C单击对话按钮向用户A发送消息,记录将不会保存,我会回滚
对话控制器:
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
错误发生在这一行
redirect_to conversation_messages_path(@conversation)
对话模型:
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 = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)", user_A, user_B, user_B, user_A)
}
end
由于这一行而发生错误
validates_uniqueness_of :sender_id, :recipient_id
【问题讨论】:
标签: ruby-on-rails ruby