簡體   English   中英

Rails作用域,按日期和子數據過濾所有

[英]Rails scopes, filtering all by date and child data

我有一個名為“廣告系列”的模型,它belongs_to “時間表”。

廣告活動具有開始和結束日期,並且時間表包含諸如“每個星期一”,“每天”等信息。

我想選擇在特定日期有效的所有廣告系列。

# campaign.rb
scope :active,      -> { where(status: true) }
scope :inactive,    -> { where(status: false) }

def valid_for(date)
  includes(:schedules).where("
        ( start_at >= ? AND (end_at IS NULL OR end_at <= ? ) )
        AND schedules.days_of_week = ?",
        date,
        date,
        date.wday
    )
end

在我的Campaign規范中(測試中確實存在Campaign和Schedule):

expect(Campaign.active.valid_for("2015-06-15".to_date).size).to eq 1

我得到的錯誤是:

undefined method `valid_for' for #<ActiveRecord::Relation []>

我不能使用的一類方法self.valid_for因為我需要能夠訪問屬性start_atend_at ,以及父調度。 但是,它似乎也不能用作實例方法。

使其成為范圍並使用范圍參數:

scope :valid_for, ->(date) {
  includes(:schedules).where("
        ( start_at >= ? AND (end_at IS NULL OR end_at <= ? ) )
        AND schedules.days_of_week = ?,
        start_at,
        end_at,
        date.wday
    ")
}

這將限制到您的訪問start_atend_at雖然。 您需要從數據庫中獲取這些參數,或者將它們作為args傳遞給您的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM