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

橙三吉。 提交于 2019-12-11 09:07:04

问题


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.

  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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!