我正在编写一个带有身份验证的简单博客,而且我遇到了一个小问题 - 我需要评论属于当前用户并显示他的名字。这样:
username:string
has_many :comments, dependent: :destroy
has_many :comments
belongs_to :post belongs_to :user
addUserIdToComments user_id:integer
@comment.user = current_user
<%= comment.user.username %>
结果我有NameError undefined local variable or method comment for #<#<Class:0xb93859dc>:0xb4b2a2b4>
我已经查看了here,但它没有帮助:(
comments_controller.rb
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.user = current_user
if @comment.save
redirect_to post_path(@post)
else
render 'comments/form'
end
end
private
def comment_params
params.require(:comment).permit(:username, :body)
end
show.html.erb
<div id="post_content">
<h2><%= @post.title %></h2>
<p><%= @post.body %></p>
</div>
<div id="comments">
<h2 class="comments">Комментариев: <%= @post.comments.count %></h2>
<%= render @post.comments %>
<%= render "comments/form" %>
</div>
_comment.html.erb
<div class="comment_content">
<p><%= comment.user.username %></p>
<p><%= comment.body %></p>
<p><%= time_ago_in_words(comment.created_at) %></p>
</div>
_form.html.erb
<div id="comment_form">
<h3 class="form_title">Оставить комментарий</h3>
<p><%= comment.user.username %></p>
<%= form_for ([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :Комментарий %>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
</div>
答案 0 :(得分:1)
我不明白什么是<%= render @post.comments %>
以及它的视图在哪里,我只看到一个评论的子视图
尝试更改
<%= render @post.comments %>
到
<% @post.comments.each do |comment| %>
<div class="comment_content">
<p><%= comment.user.username %></p>
<p><%= comment.body %></p>
<p><%= time_ago_in_words(comment.created_at) %></p>
</div>
<% end %>
或者检查您使用@post.comments