lwinhtooko lwinhtooko - 6 months ago 19
Ruby Question

Rails ActiveRecord: how to get non-duplicate child records by super-parent in view?

I have four tables called

Albums
,
Songs
,
Singers
and
SongSingers
.

Albums { Id, Name }
Songs { Id, AlbumId, Name }
Singers { Id, Name }
SongSingers { Id, SongId, SingerId }



  • Album has many songs.

  • Song belongs to an Album.

  • SongSinger belongs to Song and Singer.

  • Song and Singer have many SongSingers.



Each song may have same or different singers.

In View, how can I get all non-duplicate Singers by AlbumId.

Thanks.

Answer

Absolutely no problem.

  1. You are querying for singers. That's what the query will start with.
  2. You have a condition on songs stored in association. We'll need it soon.

    @album.songs
    
  3. Join songs and singers so you can apply the above condition. Note: you're still selecting singers! It's just that now you can place conditions on their songs.

    Singer.joins(:songs)
    
  4. Now apply it:

    Singer.joins(:songs).merge(@album.songs)
    # It's pretty much the same as this, but more concise:
    Singer.joins(:songs).merge(songs: {album_id: @album.id})
    
  5. Now filter down duplicates:

    Singer.joins(:songs).merge(@album.songs).uniq
    

Done.

Comments