I have a Model Post
and there is an array that includes post_id
like this:
hashes = [[post_id: 1, info: 'foo'],
[post_id: 3, info: 'bar'],
[post_id: 4, info: 'foobar']]
I can update models by this code.
hashes.each do |h|
post = Post.find(h[:post_id])
next if post.nil?
post.update(info: h[:info])
end
But the array size is normally over 3000, if possible I want to avoid call update
so many times. How can I implement this function without using each
loop?
It sounds like you are looking for Update records - from the documentation Updating multiple records; different col with different data
You can do like this Example:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } } Person.update(people.keys, people.values)
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.