Search code examples
sqlruby-on-railspostgresqlactiverecordarel

How to get a group of attributes associated with another group of attributes?


This should be really simple but I'm having a weird amount of trouble finding an answer. I just want a group of records associated via foreign key to another group of records. For example, if I have Song belongs_to Artist via Song.artist_id, and I have a group of Artists via Artist.where(mustache: true), I want a query that returns all the Songs belonging to all those Artists. So something like:

@songs = Artist.where(mustache: true).songs

but that actually works.


Solution

  • Song.where(artist_id: Artist.where(mustache: true).select(:id))

    Or

    song.joins(:artist).where(artists: {mustache: true})