如何允许匿名用户创建注释(Rails)

时间:2013-07-29 18:27:13

标签: ruby-on-rails devise blogs

我想允许匿名用户为帖子创建评论。在任何匿名用户创建评论后,我想在他的评论上方显示“匿名”。当注册用户发表评论时,我已经这样做了,他的名字将显示在他的评论旁边,但我怎样才能做到这一点?

博客中的身份验证系统是Devise。

comments_controller:

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 

1 个答案:

答案 0 :(得分:0)

它不优雅,但您可以使用if和||。

在您的控制器中更改:

@comment.user_id = current_user.id

@comment.user_id = current_user.id if current_user || nil

在您看来改变:

by <%=comment.user.fullname%></p>

by <%= (comment.user.fullname if comment.user) || "Anonymous" %></p>
相关问题