如果多个挑战共享同一个date
,我们怎样才能确保goal
挑战始终出现在habit
挑战之前?
challenges_controller
def index
@challenges = current_user.challenges.order("date ASC")
@challenges_by_years = (@challenges).group_by { |t| [t.date.year, t.date.month] }
end
challenge.rb
CATEGORY = ['goal', 'habit']
scope :goal, -> { where(category: 'goal') }
scope :habit, -> { where(category: 'habit') }
挑战记录
#<Challenge:0x007fd464c67b90
id: 5,
name: "Write 3 Gratitudes",
date: Mon, 06 Mar 2017,
category: "habit", # The string is always either "goal" or "habit".
user_id: 1,
答案 0 :(得分:1)
current_user.challenges.order("date ASC, category: ASC")
因为goal
小于habit
。
current_user.challenges.order(:date, :category) # a bit shorter notation, does the same thing
答案 1 :(得分:1)
您可以先按date
订购,然后按category
@challenges = current_user.challenges.order("date, category")
上述查询将按日期对记录进行排序,具有相同日期的记录将再次按类别重新排序,即'goal'
和'habit'