简体   繁体   English

Rails:检查数据库中是否已存在新记录的最有效方法

[英]Rails: Most efficient way to check if a new record already exists in DB

Lets say I have a model Product . 让我们说我有一个模型Product

Once in a while I get a file containing new products, the issue is that some of them may already have been entered into the DB. 有一段时间我得到一个包含新产品的文件,问题是其中一些可能已经输入到数据库中。

The data doesn't contain any unique key and the can come structured differently with different fields. 数据不包含任何唯一键,并且可以使用不同的字段进行不同的结构化。 What I can do is select from the DB according to all the data I have and if a product is found, not to save the one from the file. 我能做的是根据我拥有的所有数据从DB中选择,如果找到了产品,则不从文件中保存。

Product.where(:name => p.name, :desc => p.desc, :source => "some source", [more fields])

So my question is if there is a better rails way to check if the record already exists? 所以我的问题是,是否有更好的rails方式来检查记录是否已经存在?

Inserting to fail on some unique key, isn't such a good idea IMO but can work too. 插入一些独特的密钥失败,这不是一个好主意IMO,但也可以工作。

You can use the exist? 你可以使用存在吗? function like this : 功能如下:

if Product.where(:name => p.name, :desc => p.desc, :source => "some source", [more fields])
  # do something
else
  # do something else
end

You can also use the find_or_create_by if your goal is to create a new record if it does not exist like this : 如果您的目标是创建一条新记录,如果它不存在,您也可以使用find_or_create_by

Product.find_or_create_by(:name => p.name, :desc => p.desc, :source => "some source", [more fields])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM