0

我正在使用以下方法更新活动记录表:

  def sort
    params[:piece].each_with_index do |id, index|
      current_user.lineup.piece_lineups.update_all({position: index+1}, {id: id})
    end
    render nothing: true
  end

一切看起来都在工作,只是它实际上并没有将新的排序顺序保存到数据库中。查看输出,它说它正在正确更新所有内容。这是sql查询:

Started POST "/lineups/sort" for 127.0.0.1 at 2012-06-26 08:07:24 -0700
Processing by LineupsController#sort as */*
  Parameters: {"piece"=>["1", "4", "2", "3", "7"]}
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1
  Lineup Load (0.2ms)  SELECT `lineups`.* FROM `lineups` WHERE `lineups`.`user_id` = 3 LIMIT 1
  SQL (0.2ms)  UPDATE `piece_lineups` SET `position` = 1 WHERE `piece_lineups`.`lineup_id` = 4 AND `piece_lineups`.`id` = 1
  SQL (0.2ms)  UPDATE `piece_lineups` SET `position` = 2 WHERE `piece_lineups`.`lineup_id` = 4 AND `piece_lineups`.`id` = 4
  SQL (0.2ms)  UPDATE `piece_lineups` SET `position` = 3 WHERE `piece_lineups`.`lineup_id` = 4 AND `piece_lineups`.`id` = 2
  SQL (0.2ms)  UPDATE `piece_lineups` SET `position` = 4 WHERE `piece_lineups`.`lineup_id` = 4 AND `piece_lineups`.`id` = 3
  SQL (0.1ms)  UPDATE `piece_lineups` SET `position` = 5 WHERE `piece_lineups`.`lineup_id` = 4 AND `piece_lineups`.`id` = 7
  Rendered text template (0.0ms)
Completed 200 OK in 8ms (Views: 0.6ms | ActiveRecord: 1.4ms)

似乎一切都应该正常工作,但事实并非如此。我错过了什么?

4

1 回答 1

0

对不起,我认为我的回答是错误的。你的代码对我来说看起来是正确的。我不知道为什么它不起作用。但是,我看到你正在一个一个地更新片段记录,这是低效的。它将生成 O(n) 的 sql 更新查询。也许你可以试试这个,它会生成一个更新查询:

attributes = Hash[params[:piece].each_with_index.map { |id, index| [id, {order: index}] }]
current_user.lineup.piece_lineups.update(attributes.keys, attributes.values)
于 2012-06-27T00:03:19.733 回答