【问题标题】:Scope with conditions based on associated models范围与基于相关模型的条件
【发布时间】:2017-02-23 04:57:08
【问题描述】:

我正在尝试在我的 Rails 4 应用程序中编写多条件范围。

class Receipt
  # Scope to only get Receipt objects that need to be sent out.
  def self.needs_send_receipts
    where(sent_receipt: false) && company.employees.size > 0 && company.teams.first.action_items.size >= 15
  end
end

这不起作用,我试图找出原因,它应该评估为 true 并返回信息。

【问题讨论】:

  • 这个company.teams.first.action_items.size 是一个疯狂的关联链:)
  • 让我知道我的回答是否有帮助(如果您尝试过)

标签: sql ruby-on-rails ruby postgresql scope


【解决方案1】:

这是我想出的(警告:大量使用scopes):

  1. Team 模型添加一个范围,用于选择至少有15 个action_items 并且限制数量为1 的对象:

    class Team
      # company.teams.first.action_items.size >= 15
      scope :some_action_items, lambda {
        joins(:action_items)
         .group('teams.id')
         .having('COUNT(action_items.id >= 15').limit(1)
      }
    end
    
  2. Company 模型添加一个范围,用于选择至少有一个关联employee 的对象:

    class Company
      # company.employees.size > 0
      scope :with_employees, -> { joins(:employees) }
    end
    
  3. 最后,在您的Receipt 模型中使用这些范围,通过merge'ing 范围查询receipts,同时考虑所有上述条件:

    class Receipt
      # where(sent_receipt: false)
      scope :receipt_not_sent, -> { where(sent_receipt: false) }
    
      # Scope to only get Receipt objects that need to be sent out
      scope :needs_send_receipts, lambda {
        receipt_not_sent
          .joins(company: [:employees, teams: :action_items])
          .merge(Company.with_employees)
          .merge(Team.some_action_items)
      }
    end
    

我希望你意识到我什至没有机会测试它,所以如果有任何错别字/错误/等,请不要发表评论

我有一个错误提示 you have mistyped a single letter 你的解决方案 无法正常工作

但只要尝试遵循这个想法,你就会明白的:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2023-03-28
    • 2020-07-07
    • 2018-06-04
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多