按日期排序然后字符串MVC?

时间:2017-03-06 06:49:10

标签: ruby-on-rails ruby model-view-controller record

如果多个挑战共享同一个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,

2 个答案:

答案 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'