将具有多级联接的sql转换为rails activerecord表达式

时间:2012-12-13 18:08:43

标签: sql ruby-on-rails activerecord

'SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "machines"."mcln_id" = "mclns"."id" ORDER BY "mclns"."response_time" ASC'

我需要将上面的sql转换为Active record statement

complaint模型不了解mcln 它必须通过machine

Complaint.joins(:machine=>:mcln)给出了

SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "mclns"."machine_id" = "machines"."id"

但我需要

SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "machines"."mcln_id" = "mclns"."id" 

更新

一台机器可以有一个mcln,也有很多机器可以有相同的mcln。

我已经使用

实现了它 has_one :mcln模型上的

Machinebelongs_to :machine上的Mcln

而且我不确定这是否正确实施。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT complaints.*,machines.*,mclns.* FROM `complaints` 
INNER JOIN `machines` 
ON ( machines.id = complaints.machine_id )
INNER JOIN `mclns`
( ON machines.mcln_id = mclns.id )

答案 1 :(得分:0)

您的关联不正确。如果许多机器可以有相同的mcln,那么机器表应该有一个mcln_id列,你的类应该看起来像

class Machine < AR::Base
  belongs_to :mcln
end

class Mcln < AR::Base
  has_many :machines
end

然后Complaint.joins(:machine => :mcln)应生成您想要的SQL