[英]Rails update massive data
I have one model call DataIndicator
, it contains daily data, 我有一个模型调用DataIndicator
,其中包含每日数据,
And It has the following column. 并且它具有以下列。
:id => :integer,
:date => :datetime,
:dau => :integer,
:login_count => :integer
It had many data, but now I need to change some of it. 它有很多数据,但是现在我需要更改其中一些。
How do I massive update its value by date? 如何按日期大量更新其值?
EX: 例如:
The original 原本的
{ "id" => 1, "date" => 2017-01-01 00:00:00 UTC, "dau" => 5 , "login_count" => 150 },
{ "id" => 2, "date" => 2017-01-02 00:00:00 UTC, "dau" => 5 , "login_count" => 140 },
{ "id" => 3, "date" => 2017-01-03 00:00:00 UTC, "dau" => 5 , "login_count" => 300 }
Now I have a hash value, which would be referred to modify the original data. 现在,我有了一个哈希值,可以将其用于修改原始数据。
Like this 像这样
update_date = {
"2017-01-01" => {
"dau" => 5,
"login_count" => 5,
},
"2017-01-02" => {},
"2017-01-03" => {
"dau" => 5,
},
...
}
As you can see, the update_date
will not contain all attributes, it may only have one or even zero new data. 如您所见, update_date
将不包含所有属性,它可能仅包含一个甚至零个新数据。 What is the best way to update this value? 更新此值的最佳方法是什么?
I can only think about the bad one. 我只能考虑坏的。
Like this 像这样
update_date.each do |k, v|
data_by_date = DataIndicator.where(date: DateTime.parse(k)).first
next if data_by_date.nil?
data_by_date.update(v)
end
I think I misread your question. 我想我误解了你的问题。 Wouldn't it be easier if you just picked all DataIndicator records and then checked if the hash contained data for it? 如果只选择了所有DataIndicator记录,然后检查散列中是否包含数据,这会更容易吗?
DataIndicator.all.each do |di|
date = di.date.strftime("%Y-%m-%d")
to_update = update_date[date]
next if to_update.blank?
to_update.each do |field,value|
di.send("#{field}=".to_sym, value)
end
di.save!
end
This works for me. 这对我有用。
For Rails 4+ 对于Rails 4+
DataIndicator.where(["date(date) = ?"], "2017-01-01").update_all(dau: 5, login_count: 5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.