Rails named_scopes with joins

前端 未结 2 1259
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 13:53

I\'m trying to create a named_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example:

class Clip < ActiveReco         


        
2条回答
  •  长发绾君心
    2021-02-12 14:26

    The problem is that "SELECT *" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like:

    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' "
    }
    

提交回复
热议问题