【问题标题】:How do I check if a row with parameters exists and roll back transaction if it does? [RoR 6]如何检查是否存在带参数的行,如果存在则回滚事务? [RoR 6]
【发布时间】:2021-05-07 04:02:36
【问题描述】:

我是 Rails 新手,很难理解如何执行以下操作:

  1. 用户创建的条目具有两个值“名称”和“位置”。
  2. 我想检查一下 DB 中是否已经存在该名称 + 职位组合
  3. 如果是这样,我希望数据库吐出一个错误,指出名称和位置已经存在。

我认为这会很容易......只需编写:

class Rater < ApplicationRecord

  validate :unique_position, :on => :create, :on => :edit
    
private

  def unique_position
    if Rater.where(name: name, position: position).any?
      return false
    end
  end
end

我认为通过返回 FALSE,验证将不允许操作继续,但我能够创建重复项。我试过搜索网络和这个网站,尝试了不同的方法,但不确定我使用的关键字不正确。

欣赏任何方向。 ????

【问题讨论】:

    标签: ruby-on-rails validation model ruby-on-rails-6


    【解决方案1】:

    您需要在errors 对象中添加验证错误,而不是在验证失败时简单地返回false

    class Rater < ApplicationRecord
    
      validate :validate_name_and_position_uniqueness, on: [:create, :update]
        
      private
    
      def validate_name_and_position_uniqueness
        return true unless Rater.exists?(name: name, position: position)
    
        errors.add :base, 'Name and position already taken.'
      end
    end
    

    【讨论】:

      【解决方案2】:

      您可以对其他列范围内的列使用唯一性验证。 这是可以帮助您的示例。

      validates :name, presence: true, uniqueness: { scope: :position }

      validates :name, uniqueness: { scope: :position }

      *(如果名称字段不是必需的)。

      如果位置是关联,则用户position_id 具有范围的外键。

      例如:{ scope: :position_id }

      【讨论】:

      • @ArkEngel 只是想说您选择的答案符合您的要求,这很好。只是想说您也可以通过这种方式获得自定义消息。 validates :name, uniqueness: { scope: :position, message: "something is not uniq" } 这就是我们在 Rails 中的做法。但如果你想为此选择自定义方法。这需要修正。 apidock.com/rails/ActiveRecord/Base/exists%3F/class 在这种情况下会更好,而不是先 where 然后 exist?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多