0

I am getting collection of ids [1,2,3,4] in the params and I make a call to an API that will return the array for the corresponding ids. E.g. ["Apple","Orange","Mango"]. How can I update this in my database for the corresponding ids?

For example: the ids which are mentioned above are from my user table. ids = [1,2,3,4], which are primary keys in my user table.

From the API response I got an array of fruit_names for the correlated user_ids. E.g.: ids = [1,2,3,4] and fruit_names = ["a","b","c","d"], where the fruit_name column exists in my user table. How do I update fruit_name from the API response correlated ids in my user table?

4

2 回答 2

1
Hash[ids.zip fruit_names].each do |id, fruit|
  User.update_all({:fruit_name => fruit}, {:id => id})
end

或者

User.where(:id => ids).each do |usr|
 usr.update_attribute(:fruit_name, fruit_names[ids.index(usr.id)])
end
于 2013-07-17T08:30:53.993 回答
1

您可以each_with_index结合使用update

ids.each_with_index do |id, index|
  User.update(id, :fruit_name, fruit_names[index])
end

上面的代码假设:

ids = [1,2,3,4]
fruit_names = ["a","b","c","d"]

并且这些数组的索引匹配。

请注意,这将对ids数组中的每个项目执行查询。如果您的ids阵列非常大,这将不会表现良好。

于 2013-07-17T07:57:06.203 回答