gpt4 book ai didi

ruby-on-rails - Rails update_all 在一个带有索引的查询中

转载 作者:行者123 更新时间:2023-12-03 17:56:53 29 4
gpt4 key购买 nike

这是我在 Controller 中的功能:

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。

最佳答案

您是否尝试根据 :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!

除非我误解了你想要做什么......

关于ruby-on-rails - Rails update_all 在一个带有索引的查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213448/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com