简体   繁体   English

Rails:保存记录是否具有唯一值?

[英]Rails: saving a record if it has a unique value?

I'm probably searching for the wrong thing here, and I'm dumb so let me explain. 我可能在这里搜索错误的东西,我很傻,所以让我解释一下。

I have a rake task that is polling a web service every 10 minutes via cron, the response is JSON. 我有一个rake任务,它通过cron每10分钟轮询一次Web服务,响应是JSON。

For each of the items in the response I need to create a record only if a certain column has a unique value, in this case thats a hash. 对于响应中的每个项目,仅当某列具有唯一值时才需要创建一条记录,在这种情况下,这就是哈希。

Here's the meat of the task: 这是任务的内容:

response.parsed_response['items'].each do |item|
  Item.create({
    :item_hash => item['item_hash']
  })
end

The thing is that I only want to do this if the hash value is unique, is this rudimentary behavior or am I missing some obvious method in ActiveRecord? 问题是,仅当hash值唯一时才这样做,这是基本行为还是我在ActiveRecord中缺少一些明显的方法?

Use find_or_create 使用find_or_create

Item.find_or_create_by_item_hash(item['item_hash'])

If the data already exists Item is not created. 如果数据已经存在,则不会创建Item。

If you are processing lot of records I would use the following approach: 如果您要处理大量记录,则可以使用以下方法:

all_hashes = response.parsed_response['items'].map{|item| item['item_hash']}
new_hashes = all_hashes - Item.all(:select => :item_hash, 
               :conditions => {:item_hash => all_hashes}).map(&:item_hash)
Item.create(new_hashes.map{|hash| {:item_hash => hash}})

If you want to go the Railsy route, then ActiveRecord validations are the way to go, like Pan Thomakos suggested. 如果您想采用Railsy路线,则可以采用ActiveRecord验证,就像Pan Thomakos建议的那样。 There's nothing wrong with using ActiveRecord with non-form data; 对非格式数据使用ActiveRecord没什么问题; AR doesn't know (or care) where the data comes from. AR不知道(或不在乎)数据来自何处。

There's an SQL route, too: You can pair a unique index with INSERT IGNORE , and your values will only be inserted if they're unique. 也有一条SQL路由:您可以将唯一索引与INSERT IGNORE配对,并且只有它们的值唯一时才插入它们。 If you need to know whether the insert succeeded, you can kill the IGNORE and use a rescue block (you might also be able to get the "# rows changed" value back from MySQL, but I'm not sure how to do this in Rails). 如果您需要知道插入是否成功,则可以杀死IGNORE并使用急救块(您也许还可以从MySQL获取“#行已更改”值,但我不确定如何执行此操作Rails的)。

Hope this helps! 希望这可以帮助!

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

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