2013-07-03 39 views
0

我正在使用rails 3.2,並且希望使其更具動態性。我想只顯示活動作業(取決於他們在創建日期)Rails:如何使用數據庫內的條件查找記錄

class Job < ActiveRecord::Base 
    scope :is_active, lambda { where("created_at >= DATE(?)", 30.days.ago) } 
end 

我希望能夠將列添加到我的類型表的數量和底座上的查詢。

我說我的專欄,我期待這樣的事情

class Job < ActiveRecord::Base 
    belongs_to :type 
    scope :is_active, lambda { where("created_at >= DATE(?)", type.numberofdays) } 
end 

我不知道要尋找什麼,我讀過的活動記錄的文檔。如果您需要更多信息,請與我們聯繫。

+0

我認爲你需要描述多一點有什麼不工作。你是否遇到錯誤,記錄是否正確? – theIV

回答

0

我不認爲你可以在一個整數值上使用DATE()。你使用的是哪個數據庫?要查找所有屬於過去type.numberofdaysJobs,可以使用具有更新範圍的以下內容。

class Job < ActiveRecord::Base 
    belongs_to :type 
    scope :is_active, lambda { joins(:type).where("created_at >= :newer_than_date", newer_than_date: Date.today - type.numberofdays) } 
end 

更新:active_by_type

scope :active_by_type, lambda { |type| joins(:type).where("created_at >= :newer_than_date", newer_than_date: Date.today - type.numberofdays) } 
+0

你是對的,在我原來的例子中,我用的是 scope:is_active,lambda {where(「created_at> = DATE(?)」,Rails.application.config.number_of_days_for_inactive.days.ago)} 隨着你的代碼我得到了未定義的局部變量或方法'類型'爲# MathRivest

+0

你說得對,'type'將會是未定義的。由於這是一個'範圍',我認爲更好的方法是將'type'傳遞給'Job',如上面更新中所示。你怎麼看? – vee

+0

感謝您快速回答。你能更好地瞭解你的更新嗎?謝謝 – MathRivest

相關問題