目前我正在循环显示每个帖子并在该循环内循环以显示所有相关的回复。但是目前所有回复都出现在每个董事会的每个帖子下。
我如何只显示与每个帖子相关的回复?
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 %>
视图/回复/ _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 %>
答案 0 :(得分:1)
您不需要在控制器级别设置回复,因为回复属于帖子。你可以通过post.replies获得给定帖子的所有回复
在你看来
@posts.each do |post|
replies = post.replies // get all the replies that belongs to this post
replies.each do |reply|
reply.attribute
end
end
答案 1 :(得分:1)
由于您只想在_replies
中显示相关回复,请不要使用通用@replies
,请在那里使用post
:
视图/板/显示:
...
<% render "replies/replies", locals: {post: post} %>
视图/回复/ _replies :
<% post.replies.each do |reply| %>
...