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.
I referred to this article. https://qiita.com/cawaz3/items/e755a58177212f2aca6c
When you click a category tag, it opens a page by category and displays a list of posts associated with that category. ↑ Click this tag to display the post list
↑ Like this
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
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.
routes.rb
get 'posts/category/:id', to: 'posts#category'
File hierarchy is view / posts / category.html.slim