在我的 Rails 应用程序中,我有用户(作者)、帖子(文章)、评论。如果注册用户对文章发表评论,我想在他的评论旁边显示他的名字,如果他不是注册用户,我想在他的评论旁边显示“匿名”。我怎样才能做到这一点?
评论型号:
class Comment < ActiveRecord::Base
attr_accessible :post_id, :text
belongs_to :post
belongs_to :user
end
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
validates :fullname, :presence => true, :uniqueness => true
validates :password, :presence => true
validates :email, :presence => true, :uniqueness => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :fullname
end
后模型:
class Post < ActiveRecord::Base
attr_accessible :text, :title, :tag_list
acts_as_taggable
validates :user_id, :presence => true
validates :title, :presence => true
validates :text, :presence => true
belongs_to :user
has_many :comments
end
查看文件 (show.html.erb)
<h1><%= @post.title %></h1>
<p>
Created: <%= @post.created_at.strftime("%Y/%m/%d")%> by
<%= link_to @post.user.fullname, user_posts_path(@post.user) %>
</p>
<p><%=simple_format @post.text %></p>
<p>
Tags: <%= raw @post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %>
</p>
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p><%= comment.created_at.strftime("%Y/%m/%d") %>
by <%= HERE I NEED ADD SOMETHING%></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 %>
<% if user_signed_in?%>
<p>
<%= link_to "Back", posts_path %>
<%= link_to "Edit", edit_post_path(@post) %>
<%= link_to "Delete", @post, :method => :delete, :confirm => "Are you sure?"%>
</p>
<% end%>