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: 2024-11-21

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
  ZipFile
    .with_attached_zip
    .joins(:subject)
    .where(subjects: { product: downloads })
end