问题
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.
回答1:
Absolutely no problem.
- You are querying for singers. That's what the query will start with.
You have a condition on songs stored in association. We'll need it soon.
@album.songs
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)
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})
Now filter down duplicates:
Singer.joins(:songs).merge(@album.songs).uniq
Done.
回答2:
You can do this.
class Album < ActiveRecord::Base
has_many :songs
has_many :song_singers, :through => :songs
has_many :singers, :through => :song_singers
...
end
In the view, you can now simply call this
@album.singers.uniq
来源:https://stackoverflow.com/questions/30544385/rails-activerecord-how-to-get-non-duplicate-child-records-by-super-parent-in-vi