Vic*_*tor 5 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
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
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)
Run Code Online (Sandbox Code Playgroud)
显然,以上内容无法在一个查询中运行,因为我无法提升索引。
我想做的是使用在一查询中运行此命令index
。该position
应始终以启动1
基于ID数组的安排[378, 381, 380]
。
简而言之:上面的结果是正确的,但是我想在一个查询中运行它。
注意:它必须是通用SQL,必须在MySQL和Postgres中都可以使用。因为我认为该FIND_IN_SET
作品适用于MySQL,但不适用于Postgres。
您是否尝试根据属性对模型对象列表进行排序:position
?
如果是这样,我建议使用链表方法可能会更好。使用Resort gem可以轻松完成此任务。它也包含一些非常有用的辅助方法:
\n\nProduct.first_in_order # returns the first ordered product.\nProduct.last_in_order # returns the last ordered product.\nProduct.ordered # returns all products ordered as an Array, not a Relation!\n
Run Code Online (Sandbox Code Playgroud)\n\n除非我误解了你想要做什么\xe2\x80\xa6
\n 归档时间: |
|
查看次数: |
870 次 |
最近记录: |