显示 Collection 列表中每个 post 的用户头像(不重复)5

Displaying User Avatar (without duplicates) for each post in a Collection List with Rails 5

全部,

我想显示包含许多 post 的 collections 列表。

所以我在控制器中调用所有collections作为:

  def index
    @collections = Collection.order("RANDOM()")
  end

然后在视图中:

   <% @collections.each do |collection| %>

      <%= link_to collection.title, collection %>(<%= collection.posts.count %>)


      <!-- Designers (Users) -->
      <% collection.posts.each do |post_designer| %>
          <!-- I want to display designer avatars in here, I have designer_id from the post, but how do I access Designer table to pull avatar? -->
          <%= post_designer.designer_id %>
      <% end %>

      <!-- Images -->
      <% collection.posts.each do |post| %>
        <%= link_to image_tag(post.image.thumb.url.to_s, class: "fr"), collection %>
      <% end %>

   <% end %>

我的问题是:

我想在这里显示设计师头像而不是 designer_id,我有来自 post 的 designer_id,但是如何访问设计师 table 来拉头像?

谢谢!!!!


关系:

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

----------------

解决方案

看来我只是一个明显的错字! ‍♂️ 下面的代码有效,但如果用户有超过 1 个 post,它会给出重复项。如何修复重复项?

   <% collection.posts.each do |post_designer| %>
      <%= link_to image_tag(post_designer.designer.avatar.url.to_s, class: "avatar-small ml1"), post_designer, class: "fl" %>
    <% end %>

尝试像下面这样更改您的代码。它将首先为设计器获取 post,您不会看到任何重复的设计器。

<% collection.posts.select("DISTINCT ON (designer_id) *").each do |post_designer| %>
  <%= link_to image_tag(post_designer.designer.avatar.url.to_s, class: "avatar-small ml1"), post_designer, class: "fl" %>
<% end %>