2012-05-24 36 views
2

在Rails3中我怎麼檢索具有今年的日期的所有記錄? 我想找回我的所有的「項目」,其中「日期」是今年。Rails3中記錄了今年

我懷疑這將是類似於:

@projects_this_year = Project.where(:date.Time.year == Time.now.year) 
or 
@projects_this_year = Project.where(:date >= ?, Time.now.year) 

我讀通過文檔,但還沒有完全想通了這一點呢。

回答

3

你可以做這樣的事情(假設一個MySQL數據庫):

@projects_this_year = Project.where("year(date) = ?", Time.now.year)

或更好:

@projects_this_year = Project.where("year(date) = year(utc_timetamp())")

不需要加載時間庫。

參考:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

編輯


如果你希望它是獨立於數據庫,那麼你可以做這樣的事情:

@projects_this_year = Project.where("date >= ?", Time.now.at_beginning_of_year)

+0

+1的額外信息。我們想在dev下仍然保持我們的應用程序與數據庫無關,現在和不知道這對於生產的呢。由於 – Ryan

+1

接受的答案是錯的,除了語法問題,它會因爲你是比較日期與DateTime.now.year(2012)的整數值(像1337850045)任何日期返回true。看我的編輯。 – David

+0

同意。我更新了它。 –

0

你也能做出這樣動態的,如果你需要特定的幾個月或幾年經常或通過PARAMS通過擴大對@大衛answe模型R:

def self.get_year(date) 
    # sanitize if params 
    safe = ['2011', '2012', '2013'] 
    if safe.include?(date) 
     where("year(created_at) = ?", Time.parse("#{date}-01-01 11:11:11 -0500").year) 
    else 
     scoped 
    end 
end 

EX:

Product.get_year('2012') 

注:得到這個在Heroku上工作,請進行以下更改:

where("date_part('year', created_at) = ?", Time.parse("#{date}-01-01 11:11:11 -0500").year 

http://www.java2s.com/Code/PostgreSQL/Date-Timezone/datepartyeardate.htm