我想用2个变量(通知(整数)和优先级(整数[1,2,3]))对我的组进行排序。
这就是我想要达到的顺序:
1.Group with notifications
a.Group with priority(1)
b.Group with priority(2)
2. Group without notifications
a.Group with priority(1)
b.Group with priority(2)
c.Group with priority(3)
您认为最好的方法是什么?
答案 0 :(得分:2)
首先,您必须以不同方式拆分订单。对我来说,订购团队的最简单方法就是这样:
1. Group notified without priority(3)
2. Group not notified without priority(3) # We also add without priority in this step to avoid duplication
3. Group With the less priority
之后,您构建一些范围,并默认排序:
class Group < ApplicationRecord
default_scope {order(priority: asc)}
scope :notified, -> { where.not(notifications: 0, priority: 3) }
scope :not_notified, -> { where(notifications: 0).where.not(priority: 3) }
scope :not_important, -> { where(priority: 3) }
end
最后,你像这样渲染你的群体:
<% @groups = Group.all %>
<% @groups.notified.each do |group| %>
Group notified
<% end %>
<% @groups.not_notified.each do |group| %>
Group not notified
<% end %>
<% @groups.not_important.each do |group| %>
Group not important
<% end %>