如何在activerecord查询中查找数组/activerecord关系的长度或是否存在



我有两个模型:

class Listing
has_many :shipping_selections
end

class ShippingSelection
belongs_to :listing
enum status: { incomplete: 0, complete: 1 }
end

我需要编写一个查询,将返回我的列表,没有任何附加的shipping_selections与'complete'状态。

我试过这样做:

Listing.includes(:shipping_selections).where('shipping_selections.complete.any? != ?, true)

然而,我得到了以下错误:ActiveRecord::PreparedStatementInvalid:绑定变量的数量错误(1 for 2): shipping_selected .complete.any?

= ?">

似乎你不能在SQL语句中使用这样的ruby方法。

然后我尝试使用SQL语句代替,例如:

Listing.where('cardinality(shipping_selections.complete) != ?, 0')

然而,这似乎也不起作用。

谢谢你的帮助!

您得到错误的原因是因为您尝试在SQL中查询。因此,它会尝试用纯SQL读取代码,而SQL不包含任何内置的Rails函数。如果您想在SQL中查询,则需要检查status == 0而不是.complete,因为它在SQL上下文中不存在。这是内置在活动记录轨道函数中,它允许我们这样写。你要找的东西是这样的:Listing.where(shipping_selections: shipping_selections.inclomplete)

问题是您想使用ruby代码作为SQL语句。因此,当您为status字段使用enum时,您可以使用这些:

  • 获取包含完整发货选择的清单数组:
Listing.joins(:shipping_selections).merge(ShippingSelection.complete)
  • 获取包含未完成发货选择的清单数组:
Listing.joins(:shipping_selections).merge(ShippingSelection.incomplete)