How to add `:include` to default_scope?

2020-05-31 21:20发布

问题:

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?

回答1:

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.