簡體   English   中英

如何遍歷 ERB 中的 has_many:through 關聯而不產生重復項?

[英]How do I iterate through a has_many :through association in ERB without producing duplicates?

我是 Rails 新手,我正在 Rails 中創建一個相當簡單的站點,它具有三個模型:Section、Category 和 Post。 一個部分和一個類別都有很多帖子,所以邏輯上我使用帖子作為連接 model,從我的大部分測試來看,這似乎有效。 所以,我的模型如下:

class Category < ApplicationRecord
   has_many :posts
   has_many :sections, through: :posts
end

class Post < ApplicationRecord
   belongs_to :section
   belongs_to :category
end

class Section < ApplicationRecord
   has_many :posts
   has_many :categories, through: :posts
   
   has_rich_text :description

   def to_param
      url
   end
end

我在數據庫中植入了以下內容:

general = Section.create(title: "General", description: "Description of the General section", url: "general")
c1 = Category.create(title: "Cat1", description: "Desc1")
p1 = Post.create(title: "Post 1", blurb: "Blurb 1", body: "Body 1", section: general, category: c1)
p2 = Post.create(title: "Post 2", blurb: "Blurb 2", body: "Body 2", section: general, category: c1)

我現在遇到的主要問題是利用 ERB 當前部分的“顯示”頁面中的關聯。 如果我有多個 Post,它會一遍又一遍地輸出第一個迭代器,直到它用完 Posts。 這是我的ERB:

<% @section.each do |s| %>
  <% if request.path == section_path(s) %>
    <% s.categories.each do |c| %>
      <h1><%= c.title %></h1>
      <p><%= c.description %></p>
      <% c.posts.each do |p| %>
        <%= p.title %>
      <% end %>
    <% end %>
  <% end %>
<% end %>

所以,在這個例子中,它有兩個帖子。 所以它把所有的東西都打印了兩次。 這是生成的 HTML:

      <h1>Cat1</h1>
      <p>Desc1</p>
        Post 1
        Post 2
      <h1>Cat1</h1>
      <p>Desc1</p>
        Post 1
        Post 2

I'm thinking about going into the controller and doing the iterations in a hash table, and the passing the hash to the view to go over. 但是,我不覺得這會擴展,並且我最終擁有的內容越多,速度就會越慢,影響加載時間等。就 Rails 而言,我也不覺得它是慣用的,並且必須有一個更清潔的方式。 誰能告訴我我在這里做錯了什么? 提前感謝您的任何建議/幫助:)

編輯1:預期的 HTML output 只是

     <h1>Cat1</h1>
      <p>Desc1</p>
        Post 1
        Post 2

不是上面重復兩次的方式。 由於某種原因,它會重復與 Poat 數量成比例的所有內容,因此如果有 Post 3,它將顯示所有內容 3 次。 我希望所有內容都只顯示一次。

編輯 2:我可能還應該提到,在 controller, @section = Section.all

在 category 之后添加uniqdistinct可以解決這個問題

<% s.categories.uniq.each do |c| %>
  <h1><%= c.title %></h1>
  <p><%= c.description %></p>
  <% c.posts.each do |p| %>
    <%= p.title %>
  <% end %>
<% end %>

有什么不同?

  • uniq是一種 Array 方法,用於刪除數組中的重復記錄。
  • distinct是一個 ActiveRecord 方法,它在 SQL 短語中添加一個實際的DISTINCT ,它將觸發數據庫查詢。

您可以根據自己的情況選擇任何人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM