Search code examples
ruby-on-railsactiverecordassociations

Rails joins + includes of same table?


In a project at work I see a lot of code like

SomeModel.includes(:comments).joins(:comments).[...] # many more where and order clauses, other stuff

My question is: Does it make any sense to use includes and joins on the same table like :comments?


Solution

  • It may make sense. These two methods serve different purposes. You need joins if you want to filter Posts by attributes of their Comments. And you need includes to avoid N+1 queries when rendering posts with comments.