'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
模型上的 Machine
和
belongs_to :machine
上的Mcln
而且我不确定这是否正确实施。
答案 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