【问题标题】:rails console rollback on create railsrails 控制台在创建 rails 时回滚
【发布时间】: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


    【解决方案1】:

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

    正确的做法是……

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

    scoped 表示此发件人对于此收件人只能有一条记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 2013-10-11
      • 1970-01-01
      • 2012-12-22
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多