0
我正在使用 rails(5.1.4) 並嘗試顯示標記了特定類別的所有帖子。我目前只能夠返回一個帖子,而不是此類別的每個帖子。顯示所有帖子的特定類別,只返回一個結果到目前爲止 - Rails 5
Post.rb
has_many :post_categories
has_many :categories, through: :post_categories
extend FriendlyId
friendly_id :title, use: :slugged
def category_list
categories.map(&:name)
end
Category.rb:
class Category < ApplicationRecord
has_many :post_categories
has_many :posts, through: :post_categories
extend FriendlyId
friendly_id :name, use: :slugged
end
類別控制器:
def show
@category = Category.find_by_name(params[:category])
@posts = @category.posts
end
類別#顯示ERB:(這裏我試圖列出每一個崗位有這個類別,但只能得到一個結果,當我可以看到許多同一類別的帖子)
<% @posts.each do |post| %>
<h1 class="title"><%= link_to post.title, post_path(post) %></h1>
<% end %>
從終端:
Started GET "/category/Philadelphia%20maki" for 127.0.0.1 at 2017-12-17 21:03:39 -0800
Processing by CategoriesController#show as HTML
Parameters: {"category"=>"Philadelphia maki"}
Category Load (5.6ms) SELECT "categories".* FROM "categories" WHERE "categories"."name" = $1 LIMIT $2 [["name", "Philadelphia maki"], ["LIMIT", 1]]
Rendering categories/show.html.erb within layouts/dashboards
Post Load (2.0ms) SELECT "posts".* FROM "posts" INNER JOIN "post_categories" ON "posts"."id" = "post_categories"."post_id" WHERE "post_categories"."category_id" = $1 [["category_id", 15]]
路線:
category GET|POST /category/:category(.:format) categories#show
帖子#顯示ERB:
<ul class="category-list">
<% @post.category_list.map.each do |category| %></p>
<li itemprop="genre" class="category-list-item"> <%= link_to "#{category}", category_path(category) %></li>
<% end %>
</ul>
檢查'PostCategory.where(CATEGORY_ID:15).count' –
我得到一個計數,但我米身體上看到多個帖子上的標籤。我在模型中設置了錯誤嗎? – blue
獲得1意味着符合您的數據庫,您只有該職位的1個職位。 –