创建Rails上的rails控制台回滚

时间:2019-05-25 16:05:19

标签: ruby-on-rails ruby

当用户单击它时,我有一个名为“对话”的按钮,它创建对话作为数据库中的记录。问题是如果有3个用户userA,userB和userC,

如果userB单击对话按钮以向userA发送消息,它将创建良好的对话记录。但是,如果userC单击对话按钮发送消息给userA,则记录将不会保存,并且我会回滚

enter image description here

会话控制器:

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

1 个答案:

答案 0 :(得分:2)

您的唯一性应在范围内,否则,您将设置两个独立的唯一性,并且(在您的示例中)发件人在整个数据库中只能有一个对话,而收件人在整个数据库中只能有一个对话。

正确的方法是...

validates :sender_id, uniqueness: { scope: :recipient_id, message: "there is already a converation between these people" }

scoped表示该收件人与此发件人之间只有一条记录。