如何在批量更新中使用Sequel Gem返回更新的记录

时间:2015-10-20 21:08:11

标签: ruby sequel sequel-gem

我正在使用Sequel gem来批量更新MySql中的用户。

users = Users.filter(:id => ids).all
raise if users.nil?

updated_users = Users.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => 3

根据Sequel documentation

  

"更新[和删除]应返回受影响的行数..."

所以上面的行为是预期的,但我的问题是,如何让Sequel gem返回更新的记录而不是受影响的记录数?

我期待这种行为:

users = Users.filter(:id => ids).all
raise if users.nil?

updated_users = Users.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]

2 个答案:

答案 0 :(得分:0)

嗯,这就是数据库的回归,所以Sequel做了开发人员期望它做的事情。而是这样做:

users = Users.where(:id => ids)
raise if users.empty?

updated_users = Users.where(:id => addon_ids)
updated_users.update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]

这样您就不会将受影响的行数分配给updated_users

答案 1 :(得分:0)

对于可能仍在寻找此问题的人,根据您的数据库引擎,您可以使用returning

updated_users = Users.returning.filter(:id => addon_ids).update({deleted: 1, moderator_id: moderator_id})
p updated_users
# => [#<Users @values={:id=>1, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>2, :moderator_id=>"testuser", :deleted=>1}>, #<Users @values={:id=>3, :moderator_id=>"testuser", :deleted=>1}>]

文档:http://www.rubydoc.info/github/jeremyevans/sequel/Sequel%2FDataset%3Areturning