Ruby on rails 按字典哈希排序

Ruby on rails 按字典哈希排序,ruby-on-rails,database,activerecord,Ruby On Rails,Database,Activerecord,我的桌子模型是这样的 模型文件 name:string file_type:integer 然后我有一本像这样的字典 {1=>'aaa', 2=>'bbb', 3=>'ccc'} 如何对根据此词典排序的记录进行排序?如果您想使用Ruby进行排序,则可以执行以下操作: ordering = {1=>'aaa', 2=>'bbb', 3=>'ccc'} files = NiceFile.where(...).sort_by { |n| ordering[

我的桌子模型是这样的

模型文件

name:string
file_type:integer
然后我有一本像这样的字典

{1=>'aaa', 2=>'bbb', 3=>'ccc'}

如何对根据此词典排序的记录进行排序?

如果您想使用Ruby进行排序,则可以执行以下操作:

ordering = {1=>'aaa', 2=>'bbb', 3=>'ccc'}
files    = NiceFile.where(...).sort_by { |n| ordering[n.file_type] }
files = NiceFile.where(...).
                 joins('left join ordering_table on nice_file.file_type = ordering_table.file_type').
                 order('coalesce(nice_file.order_pos, 1000)').
                 limit(11)
当然,
where(…)
只是一个占位符,用于存储获取文件所需的任何操作。只要您的数据库操作都不关心排序,这就可以正常工作;在实践中,这意味着除非您计划使用
limit
offset
仅获取数据库结果的一部分,否则通常情况下这是可以的

如果需要在数据库中使用自定义排序,则需要将哈希放入一个表中(例如
ordering\u table
),加入该表,并对值进行排序。大概是这样的:

ordering = {1=>'aaa', 2=>'bbb', 3=>'ccc'}
files    = NiceFile.where(...).sort_by { |n| ordering[n.file_type] }
files = NiceFile.where(...).
                 joins('left join ordering_table on nice_file.file_type = ordering_table.file_type').
                 order('coalesce(nice_file.order_pos, 1000)').
                 limit(11)

如果您有
nice\u文件,
coalesce
left join
存在。文件类型
值不在
ordering\u表中

是散列中的键,应该是
文件类型
值吗?您想在数据库内部还是数据库外部进行排序?是的,键是文件类型。我喜欢简单的解决方案。事情不是按字典排序的——你想按键还是按值排序?