[RUBY] Display pages by category after implementing intermediate table

I implemented the category function in a many-to-many table before, but I had a hard time creating a page for each category, so I will record it.

specification

I referred to this article. https://qiita.com/cawaz3/items/e755a58177212f2aca6c image.png

What you want to achieve

When you click a category tag, it opens a page by category and displays a list of posts associated with that category. image.png ↑ Click this tag to display the post list

image.png ↑ Like this

code

ruby:posts.controller.rb


def category
    @category = Category.find(params[:id])Get the category ID you clicked here
    @post = Post.includes(:categories).where(post_category_relations: { category_id: @category })
end

I am getting the postID that matches the category ID of the intermediate table in where.

ruby:category.html.slim


.contents
  .card_header
    .card_header_title
      span.orange # 
      = @category.name Acquires and displays the category name
  .card_contents
    - @post.each do |post|Repeatedly display the acquired posts on each
      .card_item
        = link_to(post_path(post)) do
          = image_tag post.post_photo.url

Display the acquired post in view

What is includes

Rails includes is a method that can greatly reduce the number of accesses when retrieving data from multiple related tables.

In addition, it is possible to acquire data that has been searched, filtered, sorted, etc. in advance, eliminating the need for the application to perform such processing. Therefore, it becomes a simple and efficient program.

If you look at the N + 1 problem etc., you will find various things.

Related code

routes.rb


 get 'posts/category/:id', to: 'posts#category'

File hierarchy is view / posts / category.html.slim

Recommended Posts

Display pages by category after implementing intermediate table
Intermediate table is saved by assign_attributes