【问题标题】:How to use rails to find this result across 3 tables?如何使用 rails 在 3 个表中查找此结果?
【发布时间】:2009-06-10 11:35:43
【问题描述】:

一个项目有 3 个表:客户、发票、交货

关系是:

             client has_many invoices
             client has_many deliveries


              invoices belongs_to client
              deliveries belongs_to client

发票和交货模型都有一个日期字段。

现在我想查找在该月内至少有 1 条发票或交货记录的所有客户,因此需要有发票记录或交货记录或两者都有记录的不同客户。

如何使用 Rails 甚至 SQL 找到客户端?

感谢您的帮助

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    我会在客户端上定义一个方法来检查是否 交货和发票的日期在 x 月

    def has_invoice_in_month(year, month)
       start_date = Date.new(year, month, 1)
       end_date = Date.new(year, month, -1)
       invoices.each do |invoice|
         return true if start_date < invoice.date and end_date > invoice.date
       end
    end
    

    现在您遍历客户端并将它们放在一起

    Client.find(:all).collect { |c| c if c.has_invoice_in_month(y,x) or
     c.has_delivery_in_month(y,x))}.uniq
    

    uniq 调用也会删除所有返回的 nil 对象

    如果只有少数客户有发票或交货,您可以尝试获取 Client.find(:all, :join => :invoices) + Client.find(:all, :join => :deliveries)

    【讨论】:

      【解决方案2】:

      这是我第一次尝试:

      Client.all(:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => 1.month.ago])
      

      理想情况下,我想在模型中使用 named_scope 或自定义查找器方法来处理这个问题:

      class Client < ActiveRecord::Base
         named_scope :active_since, lambda {|date| {:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => date]}}
      
        # or
        def self.find_by_delivery_or_invoice_activity
          all(:include => [:deliveries, :invoices], :conditions => ['(deliveries.date > :start_date) OR (invoices.date > :start_date)', :start_date => 1.month.ago])
        end
      end
      

      我很确定这应该非常接近您的需要,但如果不针对您的情况进行一些修改,我不希望它能够工作。

      【讨论】:

        猜你喜欢
        • 2014-08-04
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 2014-08-13
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        相关资源
        最近更新 更多