当我想查找分配了特定方案的特定页面时(通过scheme_assignment),我有一些SQL工作正在运行:
Page.find_by_sql("
SELECT pages.id
FROM pages
INNER JOIN scheme_assignments ON (scheme_assignments.schemable_type = 'Page' AND
scheme_assignments.schemable_id = pages.sid)
INNER JOIN schemes ON (schemes.sid = scheme_assignments.scheme_id AND
schemes.sid IN (4,6,7))
GROUP BY pages.id")
当我尝试将其转换为ARel时:
Page.select("pages.id")
.joins("scheme_assignments")
.on("scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid")
.joins("schemes")
.on("schemes.sid = scheme_assignments.scheme_id AND schemes.sid IN (1)")
.group("pages.id")
我会收到此错误:NoMethodError: undefined method
join_sql'for“schemes”:String`
为什么?是因为它不是我Page
模型中的关联吗?可以在没有在模型中创建关联的情况下将该SQL转换为ARel吗?
答案 0 :(得分:8)
Page.joins("INNER JOIN scheme_assignments
ON (scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid)
INNER JOIN schemes
ON (schemes.sid = scheme_assignments.scheme_id AND schemes.sid IN (4,6,7))").
select("DISTINCT pages.*");
答案 1 :(得分:1)
当您建立关联时,Rails知道要使用哪种联接。我认为(虽然没试过)它应该这样工作:
Page.select("pages.id").joins("INNER JOIN scheme_assignments ON (scheme_assignments.schemable_type = 'Page' AND scheme_assignments.schemable_id = pages.sid)")...