【问题标题】:How to allow anonymous user create comments (Rails)如何允许匿名用户创建评论(Rails)
【发布时间】:2013-07-30 06:06:44
【问题描述】:

我想允许匿名用户为帖子创建 cmets。在任何匿名用户创建评论后,我想在他的评论上方显示“匿名”。我已经这样做了,当注册用户发表评论时,他的名字会显示在他的评论旁边,但是我该如何实现呢?

博客中的认证系统是Devise。

cmets_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 

【问题讨论】:

  • 这些匿名用户是注册用户吗?意思是,他们是否有 Devise 创建的用户记录,并且他们可以让 cmets 保持匿名?还是要允许非注册用户也让 cmets 保持匿名?
  • 不,匿名用户未注册。我希望没有设计用户记录的非注册用户可以将 cmets 留给帖子,并且在他们的上面 cmets 始终是“匿名的”
  • 似乎您只需要在控制器和/或视图中添加逻辑以检查current_user.id 是否存在,然后相应地显示“匿名”。您的Comment 模型必须确保user_id 的外键允许空值。

标签: ruby-on-rails devise blogs


【解决方案1】:

它并不优雅,但你可以使用 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>

【讨论】:

  • 我将它添加到控制器并查看文件,但是在我写评论(作为匿名)并按下“发表评论”之后什么也没发生。我的意思是 cmets 列表仍然是空的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2020-06-09
  • 1970-01-01
相关资源
最近更新 更多