Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将特定项目移动到最后一个位置_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 将特定项目移动到最后一个位置

Ruby on rails 将特定项目移动到最后一个位置,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,假设有一个模型项,具有属性id,名称,以及数据库中具有名称的特定记录“其他” 如何在单个SQL查询中获取一个ActiveRecord::Relation对象,该对象中的项按other项位于最后位置的方式排序? 作为临时解决方案,我使用了Item.where.not(name:'other')+Item.where(name:'other'),但它会导致两个查询 注意:这不是一个真正的代码,而是一个极其简化的示例。也许下面类似的内容会有所帮助-我们阅读所有项s,并使用slice删除项,其名称等于其

假设有一个模型
,具有属性
id
名称
,以及数据库中具有名称
的特定记录“其他”

如何在单个SQL查询中获取一个
ActiveRecord::Relation
对象,该对象中的项按
other
项位于最后位置的方式排序? 作为临时解决方案,我使用了
Item.where.not(name:'other')+Item.where(name:'other')
,但它会导致两个查询


注意:这不是一个真正的代码,而是一个极其简化的示例。

也许下面类似的内容会有所帮助-我们阅读所有
s,并使用slice删除
,其
名称
等于
其他
,并将其追加到末尾的数组中

a = Item.all.tap do |arr|
    arr << arr.slice!(arr.index { |t| t.name == "other"})
end
a=Item.all.tap do | arr|

arr如果我理解正确,那么您正在寻找SQL查询,对吗?然后你可以试试这样的东西:

select id, name
from (
  select id, name, decode(name, 'other', 999, 1) as sort 
  from items
)
order by sort
我现在没有数据库来测试这个语句。但我想你明白了


祝您好运

通过将类方法添加到
模型中解决:

def self.sorted
  find_by_sql("SELECT * FROM items ORDER BY (CASE name WHEN 'other' THEN 0 ELSE 1 END) DESC, id ASC")
end

您可以使用@Vinay,
即时加载
用于关联记录。事实并非如此。