复杂的 AR 查询,where 子句一列等于另一列的值?

1 mysql activerecord ruby-on-rails

我已经编写了下面的 AR 查询,但是 where 子句有一个问题。在Payout模型上有 a comp_builder_id,在 acomp_builder_id上也有a ContractLevel

我想在此查询中添加一个 where 子句以获取Payout模型comp_builder_id等于ContractLevel模型的数据comp_builder_id

payouts = Payout.includes(:comp_builder => { 
                                    :contract_levels => { 
                                        :transmittal => [
                                            {:appointment_hierarchies => :child}, 
                                            :appointment_cases
                                        ] 
                                    } 
                                })
                                .includes(:product)
                                .includes(:payor)
                                .where(products: { :id => self.product.id })
                                .where(appointment_cases: { :case_id => self.id })
                                .where(transmittals: { :id => appointment_case.transmittal_id })
                                .where(contract_levels: { :transmittal_id => appointment_case.transmittal_id, 
                                                          :appointment_id => Transmittal.find(appointment_case.transmittal_id).low,
                                                          :comp_builder_id => # ? payout's comp builder id ?  })
Run Code Online (Sandbox Code Playgroud)

如何在 Active Record 中做到这一点?在我引用不同变量的最后几个 where 子句中,这些可以被忽略,因为这个查询只是一个片段。

nma*_*jor 5

您可以将字符串传递到 where 语句中:

User.include(:parent).where('users.parent_id = parents.id')
Run Code Online (Sandbox Code Playgroud)

基本上,如果您知道希望 where 语句在原始 SQL 中的样子,那么您只需将其作为字符串传入 where 语句即可。

这是我所知道的在 ActiveRecord 中制作复杂 where 语句的唯一方法。

请务必记住,您需要引用列名称,而不是模型名称。