带有连接的Rails named_scopes

时间:2008-10-03 10:20:41

标签: ruby-on-rails ruby activerecord named-scope

我正在尝试创建一个使用连接的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。我哪里错了?

2 个答案:

答案 0 :(得分:26)

问题是“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' "
}

答案 1 :(得分:5)