【问题标题】:Rails ActiveRecord: how to get non-duplicate child records by super-parent in view?Rails ActiveRecord:如何通过超级父视图获取不重复的子记录?
【发布时间】:2015-05-30 09:18:54
【问题描述】:

我有四个表,分别名为 AlbumsSongsSingersSongSingers

Albums { Id, Name } 
Songs { Id, AlbumId, Name }
Singers { Id, Name }
SongSingers { Id, SongId, SingerId }
  • 专辑有很多歌曲。
  • 歌曲属于专辑。
  • SongSinger 属于 Song 和 Singer。
  • Song 和 Singer 有很多 SongSinger。

每首歌可能有相同或不同的歌手。

在 View 中,我如何通过 AlbumId 获取所有不重复的 Singers。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

    绝对没问题。

    1. 您正在查询歌手。这就是查询的开头。
    2. 您对关联存储的歌曲有条件。我们很快就会需要它。

      @album.songs
      
    3. 加入歌曲和歌手,以便您可以应用上述条件。注意:您仍在选择歌手!只是现在你可以给他们的歌曲设置条件了。

      Singer.joins(:songs)
      
    4. 现在应用它:

      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. 现在过滤掉重复项:

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

    完成。

    【讨论】:

    • 完美运行。谢谢老兄。
    【解决方案2】:

    你可以这样做。

    class Album < ActiveRecord::Base
    
      has_many :songs
      has_many :song_singers, :through => :songs
      has_many :singers,      :through => :song_singers
    
      ...
    
    end
    

    在视图中,您现在可以简单地调用它

    @album.singers.uniq
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多