私のレールアプリには、ユーザー(作成者)、投稿(記事)、コメントがあります。登録ユーザーが記事にコメントを書いた場合、コメントの横に彼の名前を表示したい、登録ユーザーでない場合、コメントの横に「匿名」を表示したい。これどうやってするの?
コメント モデル:
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%>