查询rails

时间:2016-02-10 07:20:16

标签: mysql ruby-on-rails ruby activerecord

广告系列包含属性:start_date,:end_date

发票包含属性:start_date,:end_date

campaign.rb

has_many:invoices

invoice.rb

belongs_to:campaign

我希望得到start_date小于当前日期AND end_date介于campaign.invoices.last.created..current_date

之间的所有cmapaigns

我如何查询?

3 个答案:

答案 0 :(得分:3)

试试这个:

 Compaign.joins(:invoices)
            .where("compaigns.start_date < :today AND compaigns.end_date < :today", today: Date.today)
            .group("compaigns.id")
            .having("compaigns.end_date > MAX(invoices.created_at)")

答案 1 :(得分:2)

我从未使用Rails魔法对数据库执行或多或少的复杂请求。它总是导致巨大的开销,N + 1查询或一些意外的处罚。以下是执行此任务的普通旧SQL版本:

Campaign.connection.execute <<-SQL
   SELECT campaigns.*, last_invoice_date
   FROM campaigns 
     JOIN (
       SELECT invoices.campaign_id AS campaign_id,
              MAX(invoices.started) AS last_invoice_date
       FROM invoices
       GROUP BY invoices_campaign_id
     ) AS last_invoices
     ON (last_invoices.campaign_id = campaigns.id)
     WHERE campaigns.start_date < NOW()
       AND campaigns.end_date < NOW()
       AND campaigns.end_date >= last_invoices.last_invoice_date
SQL.to_a

上述情况并未因显而易见的原因进行测试,但它应该按原样或稍作修改。

答案 2 :(得分:1)

campaigns = Campaign.where("DATE(start_date) < ?", Date.today).includes(:invoices)

invoices = campaigns.each do |campaign|
              campaign.invoices.where("Date(campaigns.end_date)" BETWEEN campaign.invoices.last.created_at.to_date AND Date.today)
           end

invoices.map(&:campaign)