简体   繁体   中英

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. Also the method #update_all does not work as I have individual data to update each record depending on 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.

There could be about 10,000 - 100,000 records to update.

Env: Postgres 9.4, Rails 3 (also if there is a good solution in Rails4 would appreciate to hear about)

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. 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. Some things are just better done in the DB because that is what it's designed to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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