Display ALL posts with specific category, only returning one result so far- Rails 5

时间:2017-12-18 05:10:11

标签: ruby-on-rails categories

I am using rails (5.1.4) and trying to show all posts tagged with a specific category. I am currently only able to return one post instead of every post with this category.

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

Category Controller:

def show
    @category = Category.find_by_name(params[:category])
    @posts = @category.posts
end

Category#show ERB: (where I am attempting to list every post with this category, but only getting one result, when I can physically look to see many posts with that same category)

 <% @posts.each do |post| %> 
   <h1 class="title"><%= link_to post.title, post_path(post) %></h1>
 <% end %>

From the Terminal:

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]]

Routes:

category GET|POST /category/:category(.:format) categories#show

Posts#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>

1 个答案:

答案 0 :(得分:0)

For users visiting this page,

Problem

User was seeing multiple posts with the same category name on a different page but when fetching posts of that category, it was returning only 1 post.

Cause

There were multiple Category records in the database with the same name.

Solution

Add a validation to model Category:

validates :name, uniqueness: true, allow_blank: true