通过 Rails 的关系集合按 has_many 中的用户对帖子进行分组 5
Grouping posts by user in has_many through relation collection with Rails 5
我正在尝试在集合中显示用户(设计)(has_many 通过)。
<%= @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 %>
但它显示重复
我需要按 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
...
关系:
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
首先需要找到uniq设计师id
designer_ids = @collection.posts.distinct.pluck(:designer_id)
然后通过这些id找到设计师
@designers = Designer.where(id: designer_ids)
我正在尝试在集合中显示用户(设计)(has_many 通过)。
<%= @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 %>
但它显示重复
我需要按 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
...
关系:
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
首先需要找到uniq设计师id
designer_ids = @collection.posts.distinct.pluck(:designer_id)
然后通过这些id找到设计师
@designers = Designer.where(id: designer_ids)