2013-07-29 26 views
0

我想允許匿名用戶對帖子創建評論。任何匿名用戶創建評論後,我想在評論上方顯示「匿名」。當註冊用戶發表評論時,我已經這樣做了,他的名字將顯示在他的評論旁邊,但我怎麼能做到這一點?如何讓匿名用戶創建評論(Rails)

博客中的身份驗證系統是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

這些匿名用戶是註冊用戶嗎?意思是說,他們是否有由Devise創建的用戶記錄,並且他們可以將評論留爲匿名?還是你想讓非註冊用戶也可以匿名發表評論? – richsinn

+0

不,匿名用戶未註冊。我希望那些沒有用戶記錄的非註冊用戶可以留言給他們,他們的評論總是「匿名」的。 – user2596615

+0

好像你只需要在控制器中添加邏輯和/或查看是否存在'current_user.id',然後相應地顯示「匿名」。您的'Comment'模型將必須確保'user_id'的外鍵允許空值。 – richsinn

回答

0

這不是優雅,但你可以使用,如果和||。

在你的控制人變更情況:

@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> 
+0

我添加到控制器和查看文件,但在我寫評論(作爲匿名),並按'後評論'沒有發生任何事情。我的意思是評論清單仍然是空的 – user2596615