Rails嵌套连接条件的Activerecord

时间:2014-08-04 03:35:51

标签: sql ruby-on-rails rails-activerecord

我正在尝试使用条件编写嵌套连接查询。

我现在的查询是:

Event.joins(:store => :retailer).where(store: {retailer: {id: 2}})

哪个输出以下SQL:

   SELECT "events".* FROM "events" INNER JOIN "stores" ON "stores"."id" = "events"."store_id" INNER JOIN "retailers" ON "retailers"."id" = "stores"."retailer_id" WHERE "store"."retailer_id" = '---
:id: 2
'

还有以下错误:

SQLite3::SQLException: no such column: store.retailer_id: SELECT "events".* FROM "events" INNER JOIN "stores" ON "stores"."id" = "events"."store_id" INNER JOIN "retailers" ON "retailers"."id" = "stores"."retailer_id" WHERE "store"."retailer_id" = '---
:id: 2
'

它告诉我没有列store.retailer_id,但是,我可以运行以下查询,它可以正常工作:

Event.first.store.retailer_id
  Event Load (0.2ms)  SELECT  "events".* FROM "events"   ORDER BY "events"."id" ASC LIMIT 1
  Store Load (0.1ms)  SELECT  "stores".* FROM "stores"  WHERE "stores"."id" = ? LIMIT 1  [["id", 28958]]
=> 4

3 个答案:

答案 0 :(得分:27)

看起来你不需要嵌套连接。尝试使用像

这样的东西
Event.joins(:store).where(stores: {retailer_id: 2})

嵌套连接也应该使用stores

Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}})

答案 1 :(得分:4)

最简单的方法是使用大括号:

Event.joins(:store => :retailer).where('stores.retailer_id => ?', 2)

答案 2 :(得分:1)

您应该能够使用以下语法访问retailers id

Event.joins(:store => :retailer).where('retailers.id' => 2)

PS。在Rails 5上测试