在一个带索引的查询中使用Rails update_all

时间:2012-04-18 16:08:34

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

这是我在我的控制器中的功能:

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)

显然上面没有在一个查询中运行,因为我无法让索引升级。

我想要做的是在index的一个查询中运行此功能。 position应始终以1为基础,基于id数组[378, 381, 380]的排列。

简而言之:上面的结果是正确的,但我想在一个查询中运行它。

注意:它必须是通用SQL,它必须同时适用于MySQL和Postgres。因为我认为FIND_IN_SET适用于MySQL,而不适用于Postgres。

2 个答案:

答案 0 :(得分: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!

除非我误解了你想要做的事情,否则......

答案 1 :(得分:0)

不知道它会有多大帮助但是我使用下面的代码让这个插件运行,模型即时分类是步骤

的Gemfile

$(document).ready(function(){
$("div.page-content div.page").hide();
$(".page-content div.page:first-child").show();

  $("a.edit").click(function() {    // EDIT BUTTON
    $("div.page-content .page").hide("slide", { direction: "left" }, 1000);
    $($(this).attr("href")).delay(1000).toggle('slide', { direction: "right" }, 1000);
  });

  $("a.back").click(function() {    // BACK BUTTON
     $("div.page-content .page").hide("slide", { direction: "left" }, 1000);
     $($(this).attr("href")).delay(1000).toggle('slide', { direction: "right" }, 1000);
  });
}); 

要求在application.js

# Use jquery-ui
gem 'jquery-ui-rails', '~> 5.0', '>= 5.0.5'

查看:(我用了一张桌子,但是ul也有效 在表体中添加:

//= require jquery_ujs

对于每个表格行添加:

<tbody id="steps" data-update-url="<%= sort_course_steps_url %>">

Javascript:应用可排序和后序列化数据

<tr id="step_<%= step.id %>">

路线

jQuery(function() {
  return $('#steps').sortable({
    axis: 'y',
    update: function() {
     return $.post($(this).data('update-url'), $(this).sortable('serialize'));
    }
  });
});

控制器:

resources :steps do
    collection {post :sort}
end