How to create an association without has many and friends

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

Last Updated: 2021-05-15

Sometimes you want to create fake association - e.g. all the zip_files associated with a Product, but you don't want to / can't built the association using has_many throughs and friends.

The trick is to combine a joins clause (to get the related tables), with a nested where clause, to work with the conditions, and some data based on an existing method (e.g. the downloads method, already existent.)

def zip_files
    .where(subjects: { product: downloads })