我有一系列活动记录对象,我想按特定顺序排序。
可能有0到5个结果:
[#<Milestone id: 657708, event_id: 2426, event_type: "Part", data_type: "setup_required", date_at: "2014-11-13 06:27:05", user_id: 1003>, #<Milestone id: 657707, event_id: 2426, event_type: "Part", data_type: "setup_ready", date_at: "2014-11-13 06:27:05", user_id: 1003>]
这是我要按其排序的数组。
status = %w[setup_ready setup_required bom_processing pending_approval part_live]
我想针对数组元素对data_type进行排序。
所以在这种情况下,我的结果将是:
[#<Milestone id: 657707, event_id: 2426, event_type: "Part", data_type: "setup_ready", date_at: "2014-11-13 06:27:05", user_id: 1003>, #<Milestone id: 657708, event_id: 2426, event_type: "Part", data_type: "setup_required", date_at: "2014-11-13 06:27:05", user_id: 1003>]
建议后的代码:
milestones = Milestone.where(event_id: params[:id])
status = %w[setup_ready setup_required bom_processing pending_approval part_live]
@part_milestones = milestones.sort_by {|m| status.index(m.data_type)}
milestones = [#<Milestone id: 657708, event_id: 2426, event_type: "Part", data_type: "setup_required", date_at: "2014-11-13 06:27:05", user_id: 1003>, #<Milestone id: 657707, event_id: 2426, event_type: "Part", data_type: "setup_ready", date_at: "2014-11-13 06:27:05", user_id: 1003>]
@part_milestones = [#<Milestone id: 657708, event_id: 2426, event_type: "Part", data_type: "setup_required", date_at: "2014-11-13 06:27:05", user_id: 1003>, #<Milestone id: 657707, event_id: 2426, event_type: "Part", data_type: "setup_ready", date_at: "2014-11-13 06:27:05", user_id: 1003>]
通过添加to_s:
解决@part_milestones = milestones.sort_by {| m | status.index(m.data_type.to_s)}
答案 0 :(得分:1)
假设milestones
包含Milestone ActiveRecord对象的集合:
milestones = Milestone.all
status = %w[setup_ready setup_required bom_processing pending_approval part_live]
sorted_milestones = milestones.sort_by {|m| status.index(m.data_type)}
如果状态列表中不存在任何里程碑data_types,则应将它们排序到数组的末尾。