如何将查询直接传递给where条件?

How to pass query directly to the where condition?

查询:

Vendor.where(vendors: {company: nil}).joins(technologies_vendors: {technology_id: "Technology.select(:technology_id).where(url: 'ios',is_verified: true)"})

错误:

ActiveRecord::ConfigurationError: Association named 'technology_id' was not found on TechnologiesVendor; perhaps you misspelled it?

我假设您已经设置了三个具有以下关系的模型:

Vendor has_many technologies_vendors
Technology has_many technologies_vendors
TechnologiesVendor belongs_to vendor
TechnologiesVendor belongs_to technology

您的条件是:

vendors should have 'nil' company
technologies should be verified and have 'ios' url

这样的话,这就是你想要的:

Vendor.
joins(technologies_vendors: :technology).
where({
  vendors: {company: nil},
  technologies: {url: 'ios', is_verified: true}
})

但是您也可以很容易地使用 merge 方法。

Vendor.
joins(technologies_vendors: :technology).
where(vendors: {company: nil}).
merge( Technology.where(technologies: {url: 'ios', is_verified: true}) )

然而,在这两种情况下,您都必须消除或稍微修改您的第二个查询。

Learn more about merge here.