Select statements that do not include the id column will break joins

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2024-04-19

I had the following code:

@law_cases = LawCase.select(:slug, :name).include(:law_disciplines)

In the controller I had the following:

@law_case.law_disciplines.pluck(:name)

The output of this controller code turned out to always be unexpectedly empty (i.e. containing 0 names).

This turned out to be due to the law of :id column in the select for the parent LawCase. Without that id column, the joins broke down. Once I added :id back into the select statement, everything worked again.

Lesson

Always include ids in your select statement if you plan on joining. (In fact, it's probably a good idea to grab them just in case in all situations that aren't performance bottlenecks.)