I'm trying to display Users (devise) in a collection (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 %>
but it displaying duplicates as in
I need to group by designer.id. So I added @collection_designers line but I could not manage to group by designer 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
...
Relations:
models/collection.rb
class Collection < ApplicationRecord
belongs_to :designer
has_many :collectivizations
has_many :posts, through: :collectivizations
end
models/collectivization.rb
class Collectivization < ApplicationRecord
belongs_to :post
belongs_to :collection
end
models/post.rb
class Post < ApplicationRecord
belongs_to :category
belongs_to :designer
has_many :collectivizations
has_many :collections, through: :collectivizations
You need to find uniq designers ids at first
designer_ids = @collection.posts.distinct.pluck(:designer_id)
And after it find designers by these ids
@designers = Designer.where(id: designer_ids)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.