用户通过与Rails 5的关系集合在has_many中对用户进行分组

时间:2018-03-06 11:03:16

标签: sql ruby-on-rails group-by ruby-on-rails-5 has-many

我试图在集合中显示用户(设计)(has_many through)。

    <%= @collection.posts.count %> designs by
    <% @collection.posts.each do |post| %>
      <%= link_to image_tag(post.designer.avatar.url.to_s, class: "avatar-small"), post.designer %>
    <% end %>

但它显示重复项,如

enter image description here

我需要按照designer.id进行分组。所以我添加了@collection_designers行,但我无法按照设计师id.♂️

进行分组
class CollectionsController < ApplicationController

  def show
    @collection = Collection.find(params[:id])

    #I need to group for designer.id I guess but I could not manage it
    @collection_designers = Collection.find(params[:id]).groups(designers.id) 
  end

  ...

关系:

模型/ collection.rb

class Collection < ApplicationRecord
  belongs_to :designer
  has_many :collectivizations
  has_many :posts, through: :collectivizations
end

模型/ collectivization.rb

class Collectivization < ApplicationRecord
    belongs_to :post
    belongs_to :collection
end

模型/ post.rb

class Post < ApplicationRecord
  belongs_to :category
  belongs_to :designer
  has_many :collectivizations
  has_many :collections, through: :collectivizations

1 个答案:

答案 0 :(得分:-1)

您首先需要找到uniq设计师ID

designer_ids = @collection.posts.distinct.pluck(:designer_id)

之后通过这些ID找到设计师

@designers = Designer.where(id: designer_ids)