2016-10-12 50 views
1

嗨我正在開發一個項目,並且作爲其中的一部分,我希望能夠獲取在過去7天內創建的所有帖子。我已經試過:獲取在特定時間段內創建的記錄

@weeks_posts = Post.where(date: Date.today) 
    for i in 1..6 
     @weeks_posts = @weeks_posts + Post.where(date: (Date.today).to_time - i.days) 
    end 

然而這最終返回一個數組,這意味着我不能鏈.where條款給它,這是我需要做的,似乎也相當低效。

任何幫助將不勝感激。

回答

1

您可以使用scope使其靈活:

scope :by_dates, ->(start_date, end_date) { Post.where(date: start_date..end_date) } 

Post.by_dates(Date.today - 6.days, Date.today) # returns AR collection 
+0

我寧願在'where'使用範圍。 – Ilya

+0

@伊利亞使總感,編輯 –

1

嘗試是這樣的:

Post.where(date: 1.week.ago.beginning_of_day..Time.now) 
+0

很簡單:-)謝謝 – doem

相關問題