これが私のコントローラーの私の機能です:
def sort
params[:state].each_with_index do |id, index|
State.update_all({:position => index+1, :country_id => params[:country_id]}, {:id => id})
end
render :nothing => true
end
ここに私の出力があります:
Started POST "/countries/83/states/sort" for 127.0.0.1 at Thu Apr 19 00:02:56 +0800 2012
Processing by StatesController#sort as JS
Parameters: {"country_id"=>"83", "state"=>["378", "381", "380"]}
ApplicationController::current_user_session
Country Load (0.3ms) SELECT `countries`.* FROM `countries` WHERE `countries`.`id` = 83 LIMIT 1
SQL (1.0ms) UPDATE `states` SET `country_id` = '83', `position` = 1 WHERE `states`.`id` = 378
SQL (1.4ms) UPDATE `states` SET `country_id` = '83', `position` = 2 WHERE `states`.`id` = 381
SQL (0.9ms) UPDATE `states` SET `country_id` = '83', `position` = 3 WHERE `states`.`id` = 380
SQL (0.6ms) UPDATE `countries` SET `updated_at` = '2012-04-19 00:02:56' WHERE `countries`.`id` = 83
Rendered text template (0.0ms)
Completed 200 OK in 559ms (Views: 13.0ms | ActiveRecord: 39.3ms | Sphinx: 0.0ms)
明らかに、インデックスをステップアップさせることができなかったため、上記は 1 つのクエリでは実行されません。
私がやりたいことは、これをindex
. id 配列の配置に基づいて、position
常に で始まる必要があります。1
[378, 381, 380]
簡単に言うと、上記の結果は正しいですが、1 つのクエリで実行したいと考えています。
注: これは、MySQL と Postgres の両方で機能する汎用 SQL でなければなりません。MySQLでは機能すると思いますFIND_IN_SET
が、Postgresでは機能しないからです。