带条件的订单元素
Order element with condition
我想用 2 个变量 (notifications(integer) & priority(integer[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)
您认为最好的方法是什么?
首先,您必须以不同方式拆分订单。对我来说,订购群组的最简单方法是这样的:
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 %>
我想用 2 个变量 (notifications(integer) & priority(integer[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)
您认为最好的方法是什么?
首先,您必须以不同方式拆分订单。对我来说,订购群组的最简单方法是这样的:
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 %>