2017-03-06 9 views
0

複数の課題が同じである場合dateどうすればのチャレンジをいつでも表示することができます。habitのチャレンジの前に必ず表示されますか?日付順の文字列MVC?

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, 

答えて

1

あなたがで注文することができdate最初にしてORDER BY category日付別レコードと同じ日付のレコードを注文します上記のクエリは、再度、カテゴリ別に並べ替えます

@challenges = current_user.challenges.order("date, category") 

すなわち'goal''habit'

+0

「カテゴリ」による順序付けは、「習慣」の前に「ゴール」にデフォルト設定されています。より少ない文字の英字かスコープ・ラインの順序ですか? –

+1

文字列がアルファベット順であるので、 'g 'は' h'の前に来ます –

1
habit未満であるため、10

です。

current_user.challenges.order(:date, :category) # a bit shorter notation, does the same thing