18

Searching the 'net, I found that I should use :include, but that does not seem to change the SQL query that is generated:

def Post #model
  default_scope :order => 'created_at DESC', :include => :author
end

With or without the :include, the SQL is the same (i.e. it is only selecting from the posts table).

What is the way to do this?

Zabba
  • 64,285
  • 47
  • 179
  • 207

1 Answers1

34

What if you do

default_scope { includes(:author).order('created_at ASC') }

This is the way that it’s documented in the Rails API for default_scope & scope, rather than the hash parameter method you're using.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • Yes, using that style, but with `includes` (plural), works. Also found that using the hash-style, using `:joins` instead of `:include` works. – Zabba Feb 21 '11 at 23:39
  • Include on its own is usually interpreted as the Ruby include keyword and it doesn't like it :) – Ghoti Dec 18 '14 at 14:14
  • @Ghoti `include` isn’t a keyword, it’s a method (`defined?(include) #=> "method"`), and thus *could* be overridden. Of course `:include` is just an unrelated symbol. – Andrew Marshall Dec 18 '14 at 14:36
  • 1
    in rails 4 you must use blocks for this `default_scope { includes(:author) }` – jtmarmon Aug 11 '15 at 21:29