0

匿名ユーザーが投稿にコメントできるようにしたい。anonユーザーがコメントを作成した後、コメントの上に「匿名」を表示したいと思います。登録ユーザーがコメントを残すと、そのユーザーの名前がコメントの横に表示されるようにしましたが、どうすればこれを達成できますか?

ブログ内の認証システムは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 
4

1 に答える 1

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>
于 2013-07-29T22:06:44.597 に答える