aidiah aidiah - 6 months ago 18
Ruby Question

Only show replies realted to post

Currently I'm looping to show each post and inside that loop looping to show all related replies. However currently all replies are showing up under every post on every board.

How can I only show the replies that are related to each post?

resources :boards, :path => '' do
resources :posts, :path => 'thread' do
resources :replies

class BoardsController < ApplicationController
def show
@board = Board.friendly.find(params[:id])
@boards = Board.all
@replies = Reply.all
end

class PostsController < ApplicationController
def show
@board = Board.friendly.find(params[:board_id])
@boards = Board.all
@replies = Reply.all
@post = Post.includes(:board).where('boards.slug' => params[:board_id]).friendly.find(params[:id])
end

class Board < ActiveRecord::Base
has_many :posts
has_many :replies, through: :posts
include FriendlyId
friendly_id :name, use: :slugged
accepts_nested_attributes_for :posts, :replies
end

class Post < ActiveRecord::Base
belongs_to :board
has_many :replies, dependent: :destroy
accepts_nested_attributes_for :replies
include FriendlyId
friendly_id :pid, :use => :scoped, :scope => :id
end


views/boards/show:

<% @board.posts.find_each do |post| %>
<%= post.subject %>
<%= post.name %>
<%= post.email %>
<%= post.created_at %>
No.<%= post.pid %>
<%= link_to "[reply]", board_posts_path(@board, @post)%>
<br>
<%= post.comment %><br><br>
<% render "replies/replies" %>
<% end %>


views/replies/_replies:

<% @replies.each do |reply| %>
<p>
>><%= reply.name %>
<% reply.created_at %>
<%= reply.email %>
<%= reply.subject %>
<%= reply.created_at.strftime("%m/%d/%Y(%a) %I:%M:%S ") %>
No.<%= reply.pid %>
<br>
<%= reply.comment %>
</p>
<% end %>

Answer

you don't need to set replies at controller level as replies belongs to posts. you can get all the replies for a given post by post.replies

in you view

@posts.each do |post|
  replies = post.replies // get all the replies that belongs to this post
  replies.each do |reply|
    reply.attribute
  end
end
Comments