The Spaghetti Refactory Established 2015

Joining two join tables in Rails

Joining data from two join tables in Rails is gross, but sometimes necessary.

Let’s say I have a join table items_categories and a join table items_groups. I want to get all items that are in the same category and the same group, by category and by group ids. Here's how I did it:

Item.joins(:items_groups).joins(:items_categories).
where('items_categories.category_id = ?', category_id).
where('items_groups.group_id = ?', group_id)


UPDATE: Since posting this, we have changed how we handle this and made a model to holds all three IDs so there is a three-way relation. This seems to be a better approach than the above, but it was fun making all those joins anyway.

Tags