我正试图创建一个使用联接的named_scope,但尽管生成的SQL看起来不错,但结果却是垃圾。例如:
class Clip < ActiveRecord::Base
named_scope :visible, {
:joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id",
:conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
}
(剪辑归系列所有,系列属于放映,放映可以是可见的,也可以是不可见的)。
Clip.all does:
SELECT * FROM `clips`
剪辑.visible.all做:
SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' )
这看起来不错。但最终得到的剪辑模型数组包括一个ID不在数据库中的剪辑,而是选择了一个节目ID。我哪里错了?
问题是"SELECT*"-查询按照剪辑、序列和显示的顺序拾取所有列。每个表都有一个id列,这会导致结果中命名列之间的冲突。(从显示中)拉回来的最后一个id列将覆盖您想要的列。您应该使用带有:joins的:select选项,如:
named_scope :visible, {
:select => "episodes.*",
:joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id",
:conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
}
这是一个错误:
http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-联接导致别名问题