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



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

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

是否有方法检查是否存在类似的记录?在SQL中,类似like%name%。

--添加。控制器中有上述内容。它有";自我;而不是"@书";,所以这可能让人感到困惑。很抱歉当我在模型中这样做时,就像下面一样,即使存在匹配的记录,它也不会阻止记录的创建,所以我把它移到了控制器:

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

您可以执行LIKE查询,如:Book.exists?("name LIKE ?", "%#{self.name}%")。请注意,使用";参数化的";查询(?(以避免SQL注入

你可以看看这个医生https://guides.rubyonrails.org/v3.2.2/security.html#sql-注入

您还可以使用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查询。

最新更新