title: Default scope for a joined table in Rails 4
body: <p>I have to select only program schedule where it belongs to a channel with ctype = TV</p>
  
  <p>but I get this error:</p>
  
  <p><img src="https://i.stack.imgur.com/B69mt.png" alt="enter image description here"></p>
  
  <p><strong>Program</strong> (Model)</p>
  
  <pre><code>class Program &lt; ActiveRecord::Base
    has_many :program_schedules, dependent: :delete_all
  </code></pre>
  
  <p><strong>ProgramSchedule</strong> (Model)</p>
  
  <pre><code>class ProgramSchedule &lt; ActiveRecord::Base
    belongs_to :program
    belongs_to :channel
  
  
    default_scope { includes(:channel).where("program_schedules.channels.ctype NOT IN (?)", ['tv']) }
  
  end
  </code></pre>
  
  <p><strong>Channel</strong> (Model)</p>
  
  <pre><code>class Channel &lt; ActiveRecord::Base
  
    validates :name, :site, :ctype, :country, :presence =&gt; true
  
    has_many :programs, :dependent =&gt; :delete_all
  </code></pre>
  
  <p><strong>QUERY</strong></p>
  
  <pre><code>@programs = Program.includes(:program_schedules).where(
                               "programs.ptype" =&gt; ["tv_show","movie"],
                                  "programs.country" =&gt; @country).
                            select("programs.id").
                            group("programs.id, program_schedules.id, channels.id").
                            having("program_schedules.stop &gt; ?", Time.current)
  </code></pre>
  
  <p><strong>Schema.rb</strong></p>
  
  <pre><code>  create_table "channels", force: true do |t|
      t.string   "site"
      t.string   "name"
      t.string   "icon"
      t.string   "ctype"
      t.string   "country"
      t.string   "lang"
      t.integer  "ordertab"
      t.datetime "created_at"
      t.datetime "updated_at"
      t.boolean  "homepage"
    end
  
        create_table "programs", force: true do |t|
      t.string "country"
      t.string "title"
      t.text   "subtitle"
      t.text   "description"
      t.float  "official_rating", default: 0.0
      t.float  "rating",          default: 0.0
      t.string "ptype"
      t.string "year"
      t.string "imdb"
      t.string "tmdb"
      t.string "tvdb"
      t.string "wiki"
      t.string "poster"
      t.string "backdrop"
      t.string "trailer"
      t.float  "popularity",      default: 0.0
    end
  
    create_table "program_schedules", force: true do |t|
      t.integer  "program_id"
      t.datetime "start"
      t.datetime "stop"
      t.integer  "channel_id"
    end
  </code></pre>