【问题标题】:Querying relations in ARel在 ARel 中查询关系
【发布时间】:2011-08-13 17:38:32
【问题描述】:

我正在做这样的事情:

@invoices = Invoice.order(:due_date)
@invoices = @invoices.where(:invoiced => true)

现在,我想通过相关模型的 id 过滤发票(我只需要发票项目所有者的 id 与某个 id 匹配的发票)。目前我正在这样做:

owner_id = #get owner_id somehow
@invoices = @invoices.find_all do |invoice|
  invoice.project.owner_id == owner_id
end

当然,这有点乱,我在控制器中做,我宁愿不做。此外,它打破了ARel的全部观点。不过,我不知道如何使用 ARel where 子句来完成上述操作。有什么想法吗?

我不能把这一切都放在一个类方法中,因为 orderwhere 用于其他代码路径,我必须为这种特殊情况复制它们(这是不对的)。

编辑:看看this related question,我可能需要使用MetaWhere 来干净利落地执行此操作。想法?

Edit2:我选择了fl00r's answer,为 Invoice 添加了范围:

#invoice.rb
scope :academic, lambda {
  academic_id = #get academic_id somehow
  joins(:project).where(:projects => { :owner_id => academic_id })
}

我还添加了invoicednot_invoiced 的作用域,因此我现在可以在我的控制器中执行@invoices.invoiced.academic,这更加简洁。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 arel


    【解决方案1】:
    @invoices = Invoice.order(:due_date).joins(:project).
      where(:invoiced => true, :projects => {:owner_id => owner_id})
    # you can also uniq the list
    @invoices.uniq!
    

    UPD

    你也可以走其他路

    @owner = Owner.find_some
    @invoices = @owner.projects.include(:invoices).map(&:invoices).flatten
    

    甚至重构一点:

    class Owner < AR::Base
      has_many :projects
      has_many :invoices, :through => :projects
    end
    
    @invoices = @owner.invoices
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多