简体   繁体   English

用哈希更新Rails中的MongoDB文档

[英]Update MongoDB document in Rails with hash

Curiosity led me to ask this question. 好奇心促使我提出这个问题。 Is any of you tried to update document/record with an hash of keys & values? 你们中有人尝试使用键和值的哈希值更新文档/记录吗? I am using rake task here. 我在这里使用耙任务。

For example I have: 例如,我有:

data = {"year" => "2015", "category" => "Action" }
movie = Movie.where(title: "Avangers").first
## some code ##
movie.save

Is there any easy way to update record with new keys and values in one line? 有没有一种简单的方法可以在一行中用新的键和值更新记录?

begin
  movie = Movie.where(title: "Avangers").first
  raise Mongoid::Errors::DocumentNotFound unless movie
  movie.update!(year: "2015", category: "Action")
rescue Mongoid::Errors::MongoidError => e
   logger.error(e.message)
end

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

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