我是 Rails 的新手,我正在 Rails 中創建一個相當簡單的站點,該站點具有三個模型:Section、Category 和 Post。Section 和 Category 都有很多帖子,所以從邏輯上講,我使用 Post 作為連接模型,從我的大部分測驗來看,這似乎有效。所以,我的模型如下:
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
我正在考慮進入控制器并在哈希表中進行迭代,并將哈希傳遞給視圖以進行檢查。但是,我不覺得這會擴展,而且我擁有的內容越多,最終會變得越慢,影響加載時間等。我也不覺得就 Rails 而言它是慣用的,并且必須有一個更清潔的方式。誰能告訴我我在這里做錯了什么?在此先感謝您的任何建議/幫助:)
編輯 1:預期的 HTML 輸出只是
<h1>Cat1</h1>
<p>Desc1</p>
Post 1
Post 2
不是上面重復兩次的方式。由于某種原因,它重復與 poats 數量成正比的所有內容,因此如果有 Post 3,它將顯示所有內容 3 次。我希望所有內容都只顯示一次。
編輯 2:我可能還應該提到在控制器中,
@section = Section.all
uj5u.com熱心網友回復:
添加uniq或distinct后分類可以解決這個問題
<% 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 方法,DISTINCT它在 SQL 短語中添加一個實際值,它將觸發資料庫查詢。
您可以根據自己的情況選擇任何人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/370148.html
上一篇:算術序列Ruby
