Ruby on rails 3 活动记录表未正确更新,但表示它在控制台中

Ruby on rails 3 活动记录表未正确更新,但表示它在控制台中,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,我正在使用以下命令更新活动记录表: 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 除了没有将新的排序顺序保存到DB之外,其他一切看起来都正常工作。查看输出,它表示正在正确更新所有内

我正在使用以下命令更新活动记录表:

  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
除了没有将新的排序顺序保存到DB之外,其他一切看起来都正常工作。查看输出,它表示正在正确更新所有内容。以下是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)

似乎一切都应该正常,但事实并非如此。我遗漏了什么?对不起,我想我的答案是错的。你的代码在我看来是正确的。我不知道为什么它不起作用。但是,我看到您正在逐个更新计件记录,这是效率低下的。它将生成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)