[英]Mass update individual records in Rails (PostgreSQL)
I have stumble on a problem to update a set of records. 我偶然发现了更新一组记录的问题。
In Database I have 在数据库中,我有
id | name | info::hstore | friends[]::varchar
1 | Claire | {} | []
2 | Mary | {} | []
3 | Bob | {} | []
I have for an example an array of hashes: 我有一个哈希数组示例:
[
{id: 1, name: "Claire", info: {age: 21, sex: 'f'}, friends: ['Mary', 'Bob']},
{id: 2, name: "Mary", info: {age: 16, sex: 'f'}, friends: ['Mike']},
{id: 3, name: "Bob", info: {age: 28, sex: 'm'}, friends: ['James']}
]
All records are already in DB, I want only to UPDATE the existent with columns from hashes, the hashes all have same number of fields to update: name, info and friends. 所有记录都已经存在于数据库中,我只想使用哈希表中的列来更新存在的表项,这些哈希表都具有相同数量的要更新的字段:名称,信息和好友。
There is a gem active-record-import but it does only inserts. 有一个gem active-record-import,但它只插入。 Also the method #update_all does not work as I have individual data to update each record depending on id. 另外,方法#update_all无效,因为我有单独的数据根据ID更新每个记录。 Don't want to make a raw SQL insert as my rows have Postgres hstore and array types, don't want to make lot of data manipulations. 不想进行原始SQL插入,因为我的行具有Postgres hstore和数组类型,也不想进行大量数据操作。
There could be about 10,000 - 100,000 records to update. 可能有大约10,000-100,000条记录要更新。
Env: Postgres 9.4, Rails 3 (also if there is a good solution in Rails4 would appreciate to hear about) Env:Postgres 9.4,Rails 3(如果在Rails4中有一个好的解决方案,不胜感激)
So I am not sure if you are against this method from what you've said so far but you could do: 因此,我不确定您到目前为止是否反对这种方法,但是可以这样做:
update_info = [{id: 1, name: "Claire", info: {age: 21, sex: 'f'}, friends: ['Mary', 'Bob']},
{id: 2, name: "Mary", info: {age: 16, sex: 'f'}, friends: ['Mike']},
{id: 3, name: "Bob", info: {age: 28, sex: 'm'}, friends: ['James']}
]
update_info.each do |row|
user = User.find(row[:id])
user.update(info: row[:info], friends: row[:friends])
end
that is about the only way to get your info from an array of hashes into the DB. 这是将您的信息从哈希数组中获取到数据库的唯一方法。 With Postgres you can do a mass update from another table with something that is similar to a join. 使用Postgres,您可以使用与联接类似的方法从另一个表进行批量更新。 But if you are going to go to all that trouble, then you should just do this on the DB console psql
or with a GUI DB program that lets you do SQL queries. 但是,如果您要解决所有这些麻烦,那么您应该仅在数据库控制台psql
或使用允许您执行SQL查询的GUI DB程序中执行此操作。 Some things are just better done in the DB because that is what it's designed to do. 在数据库中,有些事情会做得更好,因为这是设计的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.