查找两个或多个映射数组的唯一值

时间:2014-11-27 21:30:19

标签: ruby-on-rails ruby arrays map iterator

在我的项目中,我有三个模型:ArtistAlbumGenre。每位艺术家都有很多专辑,专辑有很多类型(全部通过many_to_many协会)。我想收集艺术家专辑收藏的所有类型,并过滤任何重复。例如,我有两张属于艺术家的专辑:

artist = Artist.create(name: "John Doe")

rock = Genre.create(name: "Rock")

album_one = Album.create(name: "Album One")
album_one.genres << rock

album_two = Album.create(name: "Album Two")
album_two.genres << rock

如果我使用以下方法在控制台中查询这两个专辑的这些类型,我会得到:

artist_albums = artist.albums

artist_albums.genres.map { |genre| genre.name }.uniq.join(', ')
=> Genre

我想我已接近解决这个问题。我似乎无法找回这个类型的名字。而是返回类名。

模型

class Artist < ActiveRecord::Base
    attr_accessor :name

    has_many :albums, through: album_ownerships
    has_many :album_ownerships
end

class AlbumOwnership < ActiveRecord::Base
    belongs_to :artist
    belongs_to :album
end

class Genreship < ActiveRecord::Base
    belongs_to :album
    belongs_to :genre
end

class Album < ActiveRecord::Base
    attr_accessor :name

    has_many :genres, through: :genreships
    has_many :genreships
end

class Genre < ActiveRecord::Base
    attr_accessor :name
    has_many :albums, through: :genreships
    has_many :genreships
end

控制器

def show
  @artist = Artist.find(params[:id]
  @albums = @artist.albums
end

查看

<% @albums.each do |album| %> 
  <%= album.genres.map { |genre| genre.name }.uniq.join(', ') %>
<% end %>

1 个答案:

答案 0 :(得分:0)

你可以尝试

Genre.joins(:genreships).where(genreships: { album_id: artist.albums }).uniq

按照新输入进行编辑

class ArtistsController < ApplicationController
  def show
    @artist = Artist.find(params[:id]
    @genres = Genre.joins(:genreships).where(genreships: { album_id: @artist.albums }).uniq
  end
end

现在在你看来

<%= @genres.pluck(:name).join(', ') %>