2015-10-20 60 views
1

我正在使用Sequel gem批量更新MySql中的用戶。如何在批量更新中使用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 
# => 3 

Sequel documentation

「更新[刪除]應該返回受影響的行數......」

因此上述行爲的預期,但我的問題是,我怎麼能得到續集寶石返回更新的記錄,而不是受影響的記錄數量?

我期待這種行爲:

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}>] 

回答

0

那麼,這是什麼樣的DB返回,以便續集做什麼開發人員希望它做的事。相反,這樣做:

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

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