2017-03-12 105 views
0

Ruby on Rails的:如何根據日期範圍

class Campaign < ApplicationRecord 
has_many :clicks 
has_many :cpas 
has_many :ftds 
has_many :signups 
end 

class Click < ApplicationRecord 
    belongs_to :campaign 
end 

class Cpa < ApplicationRecord 
    belongs_to :campaign 
end 

class Ftd < ApplicationRecord 
    belongs_to :campaign 
end 

class Signup < ApplicationRecord 
    belongs_to :campaign 
end 

該機型點擊,註冊會計師,FTDS查詢關係的對象,註冊是一種事件的發生這種情況一直到活動模式。我想創建一個報告頁面列出所有廣告系列,並在每行上顯示在給定時間(本月)發生的事件(點擊,cpas,ftds,註冊)(created_at)。

在我的嘗試中,我獲得了本月活動的活動,但在行中列出的數據帶來了發生在我選擇的其他月份的事件,但也是其他月份發生的事件。

def self.filter_by_date(start_date = Time.now.beginning_of_month, end_date = Time.now.end_of_month) 
    joins(:clicks).where(clicks: {created_at: start_date..end_date}) + 
    joins(:ftds).where(ftds: {created_at: start_date..end_date}) + 
    joins(:cpas).where(cpas: {created_at: start_date..end_date}) + 
    joins(:signups).where(signups: {created_at: start_date..end_date}) 
end 

對不起,英語不太好,我是巴西人。

+0

不知道這一點你被卡住時,此幫助? http://stackoverflow.com/questions/2381718/rails-activerecord-date-between –

+0

我的大問題是更多與*連接* @TonyHopkinson相關。但是,無論如何感謝:D –

+0

也許你可以添加你的查詢代碼,顯示什麼不起作用的例子? –

回答

0

Tenho certeza que sua Ingles e melhor do que o meu Portugues。如果您展示瞭如何顯示這些數據,這可能會有所幫助。正如你所寫的,它會得到所有的期間有點擊,ftds,cpas或註冊的廣告系列,然後(我假設)顯示每個廣告系列的所有點擊等。它也可能有重複的廣告系列。根據什麼你正在嘗試做的,你可以:

  • 獲取每種類型的單獨的顯示它:

    clicks = Clicks.where(created_at: start_date..end_date) 
    render_clicks(clicks) 
    ftds = Ftds.where(created_at: start_date..end_date) 
    render_ftds(ftds) 
    
  • 寫類似:

    def self.filter_by_date(start_date = Time.now.beginning_of_month, end_date = Time.now.end_of_month) 
        condition = {created_at: start_date..end_date} 
        self.includes(:clicks).where(clicks: condition) 
         .includes(:ftds ).where(ftds: condition) 
         .includes(:cpas ).where(cpas: condition)  
         .includes(:signups).where(signups: condition) 
    end 
    

這給你所有的文件,但只有在這些日期之間創建的點擊,ftds,cpas和註冊。

  • 如果你的目標是與週期之間的活動返回活動,然後就可以編寫一個查詢來做到這一點,但它是複雜的,表現不佳。我想補充一個last_activity' column to the活動table of type datetime`,然後改變你的代碼如下:

    class Click < ApplicationRecord 
        belongs_to :campaign, touch: :last_activity 
    end 
    
    class Cpa < ApplicationRecord 
        belongs_to :campaign, touch: :last_activity 
    end 
    
    class Ftd < ApplicationRecord 
        belongs_to :campaign, touch: :last_activity 
    end 
    
    class Signup < ApplicationRecord 
        belongs_to :campaign, touch: :last_activity 
    end 
    
    def self.filter_by_date(start_date = Time.now.beginning_of_month, end_date = Time.now.end_of_month) 
        where(last_activity: start_date..end_date) 
    end