5

これが私のコントローラーの私の機能です:

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では機能しないからです。

4

2 に答える 2

0

属性に基づいてモデル オブジェクトのリストを並べ替えようとしてい:positionますか?

もしそうなら、リンクされたリストのアプローチがより良いかもしれないことをお勧めします。Resort gemを使用すると、非常に簡単に実行できます。いくつかの非常に便利なヘルパー メソッドも含まれています。

Product.first_in_order # returns the first ordered product.
Product.last_in_order # returns the last ordered product.
Product.ordered # returns all products ordered as an Array, not a Relation!

あなたがやろうとしていることを私が誤解していない限り…</p>

于 2012-04-20T16:05:30.790 に答える