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

时间:2015-01-23 10:33:09

标签: mysql ruby-on-rails-4

  • 从另一个查询中获取technology_id。它是通过错误。
  • 有没有办法缩短查询。(嵌套查询)

查询:

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?

1 个答案:

答案 0 :(得分:1)

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

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.