我想允许匿名用户对帖子发表评论。在任何匿名用户创建评论后,我想在他的评论上方显示“匿名”。我已经这样做了,当注册用户发表评论时,他的名字将显示在他的评论旁边,但我该如何实现呢?
博客中的认证系统是 Devise。
评论控制器:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
@comment.user_id = current_user.id
@comment.save
redirect_to @post
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to @comment.post
end
end
从 show.html.erb 呈现评论表单的一段代码:
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p><%= comment.created_at.strftime("%Y/%m/%d") %>
by <%=comment.user.fullname%></p>
<p><%= comment.text %></p>
<p><%= link_to "Delete comment", [@post, comment],
:method => :delete, :confirm => "Are you sure?"%></p>
<% end %>
<%= form_for [@post, @post.comments.build] do |f| %>
<p><%= f.text_area :text %></p>
<p><%= f.submit "Post comment" %></p>
<% end