【问题标题】:Rails query with 'joins' and 'sum"'使用“joins”和“sum”进行 Rails 查询
【发布时间】:2017-12-24 09:31:05
【问题描述】:

我有带有“weight_fact”字段的模型 Grain_input

class GrainInput < ApplicationRecord
  has_many :movements, as: :sourceable    
end

并使用“金额”字段对运动进行建模

class Movement < ApplicationRecord
  belongs_to :sourceable, polymorphic: true
  belongs_to :targetable, polymorphic: true
end

grain_input 有很多动作。例如,grain_input 一部分从存储到设备,另一部分在别处。 我需要获取所有仍存在于存储中的grain_inputs。 适用范围:

      scope :at_storage, -> { 
            joins(:movements).
            group("grain_inputs.id").
            having("sum(movements.amount) < grain_inputs.weight_fact") }

这个范围有效,但只返回有运动的grain_inputs。 但我需要grain_inputs,它也没有动作。

请帮助修复范围。

【问题讨论】:

    标签: ruby-on-rails scope


    【解决方案1】:

    你可以试试左加入

          scope :at_storage, -> { 
            joins("LEFT JOIN `movements` ON movements.grain_input_id = grain_inputs.id" ).
            group("grain_inputs.id").
            having("sum(movements.amount) < grain_inputs.weight_fact") }
    

    【讨论】:

    • Tnx 为您的回复,但不起作用 - 结果相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    相关资源
    最近更新 更多