如何在帖子#show中显示所有评论? comments_controller
divOffset
型号:
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
@post = Post.find(params[:post_id])
@comment.user_id = current_user.id
@comment.username = current_user.username
@comment.post_id=@post.id
@comment.save
redirect_to post_path(@post)
end
def show
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:text, :username)
end
end
views / posts / show.html.erb
#app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
#app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
#app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
答案 0 :(得分:0)
在你的帖子中#show action只做:
@post = Post.find(params[:id])
@comments = @post.comments
然后在你的视图中添加:
<% @comments.each do |comment| %>
<%= comment.text %>
<br />
<% end %>
答案 1 :(得分:0)
首先修复你的帖子控制器。 show动作应如下所示:
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
@comments = @post.comments.includes(:user)
end
end
现在在app / views / posts / show.html.erb中,我会渲染一个部分:
<ul>
<%= render @comments %>
</ul>
Rails会在app / views / comments / _comment.html.erb中寻找部分内容。您可以将所有注释视图逻辑放在那里,并显示所有注释:
# app/views/comments/_comment.html.erb
<li>
<%= comment.text %>
<br>
<%= comment.user.try(:username) %>
</li>
最后,我会在评论控制器中修复你的创建动作:
class CommentsController < ApplicationController
def create
# First get the parent post:
@post = Post.find(params[:post_id])
# Then build the associated model through the parent (this will give it the correct post_id)
@comment = @post.comments.build(comment_params)
# Assign the user directly
@comment.user = current_user
if @comment.save
redirect_to post_path(@post)
else
render :new
end
end
end
在我看来,您不需要在评论模型上存储用户名属性,因为这应该通过comment.user关联提供。