Rails display Related or Similar posts from category on the post show page

1.1k views Asked by At

I have Post and category models

Post
belongs_to :category

Category
has_many :posts

On a category show page, I’m able to display a list of all posts which belongs to this category by

<% Post.where(category_id: @category.id).each do |post| %>
....
<% end %>

categories_controller ....

def show
    @category = Category.friendly.find(params[:id])
    @categories = Category.all 
end

How can I display a list of related posts which belongs to the same category (or sharing the same category id), on one of the post’s show page. Thanks!

3

There are 3 answers

3
vbyno On

I assume you may do something like this in posts_controller:

def show
  @post = Post.find(params[:id])

  @relative_posts = Post.where(category_id: @post.category_id)
end

BTW, a good practice is using scopes instead of where:

Post
belongs_to :category
scope :of_category, ->(category) { where(category_id: category) }

So that in the controller you may do

@relative_posts = Post.of_category(@post.category)
7
Ganesh On

No need to use where condition as you already have associations between Post and Category. So you can modify following code

Post.where(category_id: @category.id)

as

@category.posts

So your show action present in posts_controller.rb should look like this

def show
  @post = Post.find(params[:id])
  @relative_posts = @post.category.posts
end

Now your view should be similar to

<% @related_posts.each do |post| %>
   // disply details of individual post 
<% end %> 

Or you can avoid @related_posts variable by modifying each loop as <% @post.category.posts.each do |post| %>

Hope this will help you.

0
Charlie On

My bad, all along I was calling '@post' in the show view instead of 'post'

Controller should be:

@related_posts = Post.where(category_id: @post.category_id)

and

Post show view:

<% @related_posts.each do |post| %>
<%= post.name %>
<% end %>

Thanks all for your contributions