我正在尝试创建一个使用连接的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由一个系列拥有,一个系列属于一个Show,一个Show可以是可见的或不可见的).
Clip.all:
SELECT * FROM `clips`
Clip.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' )
这看起来还不错.但是得到的Clip模型数组包含一个ID不在数据库中的Clip - 它取而代之的是一个show ID.我哪里错了?
问题是"SELECT*" - 查询按顺序从剪辑,系列和节目中选取所有列.每个表都有一个id列,导致结果中命名列之间发生冲突.拉回的最后一个id列(从节目中)覆盖了你想要的那个.你应该使用:select选项与:join,如:
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- join-cause-alias-problem