显示具有特定类别的所有帖子,仅返回到目前为止的一个结果 - Rails 5

问题描述 投票:0回答:1

我正在使用rails(5.1.4)并尝试显示标记为特定类别的所有帖子。我目前只能返回一个帖子,而不是每个帖子都有这个类别。

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

类别#show 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

帖子#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>
ruby-on-rails categories
1个回答
0
投票

对于访问此页面的用户,

问题

用户在不同的页面上看到多个具有相同类别名称的帖子,但在获取该类别的帖子时,它只返回1个帖子。

原因

数据库中有多个Category记录具有相同的名称。

为模型Category添加验证:

validates :name, uniqueness: true, allow_blank: true
© www.soinside.com 2019 - 2024. All rights reserved.