I have a Post model:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names
belongs_to :user
has_many :comments, :dependent => :destroy
end
belongs_to :post, :counter_cache => true
belongs_to :user
end
a User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :avatar, :subscribed_tag_names
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
end
and a Comment model:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
belongs_to :user
end
This is how I show the user who created the post in the index.html.erb view:
<% @posts.each do |post| %>
<div id="post-<%= post.id %>" class="post">
<h3 class="post-title"><%= link_to post.title, post %></h3>
<div class="post-author">
<span class="profile-picture">
<%= image_tag post.user.avatar.url(:thumb) %>
</span>
<span class="post-author-name">
<strong><%= link_to post.user.username, post.user %></strong>
</span>
</div>
(etc…)
How to display the user who last commented the post (as you can see in StackOverflow and various forums)?
The previous answer only works when your post has some comments. When there are no comments then you will receive an error, as you have noted.
You could solve this by simply testing that comments exist before trying to output it: