Rails - 如何获取当前更新记录的ID(使用" update_all")?

时间:2016-06-28 22:44:26

标签: ruby-on-rails ruby activerecord

我正在更新一些记录,如下:

CarService.where("a = ? AND b = ?", a, b).update_all(color: color)

如何从上面的查询中获取已更新的记录的ID?

updated = CarService.where("a = ? AND b = ?", a, b).update_all(color: color)

仅返回0

感谢。

3 个答案:

答案 0 :(得分:0)

好吧,public static void main(String[] args) { int grades = 0; String[] students = { "1,John,Smith,John1010@fakemail.com,20,88,79,59", "2,Suzan,Erickson,Sue9999@fakemail.com ,19,91,72,85", "3,Jack,Napoli,Jack789@fakemail.com,19,85,84,87", "4,Erin,Black,Aaron888@fakemail.com,22,91,98,82" }; for (int i = 0; i < students.length; i++) { String[] student = students[i].split(","); for (int j = 4; j < student.length; j++) { grades += Integer.parseInt(student[j]); } grades=0;System.out.println(student[2] + ": " +(double) grades / (student.length - 4)); } } 返回更新的记录数。

根据您的情况,我们想到的只是先将ID存储在某处。

update_all

答案 1 :(得分:0)

update_all会返回已更新的记录数,因此您无法使用update_all&#34;来获取ID,但您可以从相同的范围。

services = CarService.where("a = ? AND b = ?", a, b)
ids = services.pluck(:id) # efficiently grab just the ids
services.update_all(color: color) # reuse the scope to update the records

答案 2 :(得分:0)

services_to_change = CarService.where("a = ? AND b = ? AND color <> ?", a, b, color)
services_to_change.update_all(color: color)
ids_of_changed_services = services_to_change.pluck(:id)