如何检查是否存在类似记录 - rails

时间:2021-04-30 01:15:53

标签: ruby-on-rails ruby

在创建新记录之前,我检查是否存在匹配的记录:

if !Book.exists?(name: @book.name) and !Book.exists?(author: @book.author) 

有没有办法检查类似记录是否存在?在 SQL 中,如 LIKE %name%。

--添加。以上是在控制器中。它有“self”而不是“@book”,所以它可能令人困惑。对不起。当我在模型中执行此操作时,如下所示,即使存在匹配的记录,它也不会阻止创建记录,因此我已将其移至控制器:

before_create :check_existing_records

def check_existing_records

  existing_book = Book.find_by(author: self.author, publisher: self.publisher)

  existing_book ||= Book.find_by(name: self.name, genre: self.genre)

  existing_book.nil?

end

2 个答案:

答案 0 :(得分:2)

您可以像这样执行 LIKE 查询:const getIO = require('../server').getIO; var io = getIO(); exports.updateSAE = (req, res) => { io.emit(); // rest of your controller function code }。请注意,使用“参数化”查询(?)来避免 SQL 注入很重要

您可以查看此文档 https://guides.rubyonrails.org/v3.2.2/security.html#sql-injection

答案 1 :(得分:1)

您还可以使用 Arel 创建 LIKE 查询:

name = 'Moby'
Book.where(Book.arel_table[:name].matches("%#{name}%"))
    .exists?

使用 Arel 以编程方式创建 SQL 而不是 SQL 字符串的很酷的部分是,您可以将其转换为灵活的类方法:

class ApplicationRecord < ActiveRecord::Base
  # @return [ActiveRecord::Relation]
  # @example
  #   Book.matches(name: 'foo').exists?
  def self.matches(**kwargs)
    kwargs.map do |key, value|
      arel_table[key].matches("%#{value}%")
    end.then do |conditions| 
      where(*conditions)
    end
  end
end

这让您可以对任何列和任何模型使用 LIKE 查询。