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
這些匿名用戶是註冊用戶嗎?意思是說,他們是否有由Devise創建的用戶記錄,並且他們可以將評論留爲匿名?還是你想讓非註冊用戶也可以匿名發表評論? – richsinn
不,匿名用戶未註冊。我希望那些沒有用戶記錄的非註冊用戶可以留言給他們,他們的評論總是「匿名」的。 – user2596615
好像你只需要在控制器中添加邏輯和/或查看是否存在'current_user.id',然後相應地顯示「匿名」。您的'Comment'模型將必須確保'user_id'的外鍵允許空值。 – richsinn