Reputation: 12739
Im new to ruby and rails, however I cant figure out why this doesnt work.
I am doing a simple Blog with posts and its comments, everything works fine but I tried to do my own method inside Post model to get the latest comment inside that post.
class Post < ActiveRecord::Base
attr_accessible :content, :title
has_many :comments
def latestComment(id)
post = Post.find(id)
comment = post.comments.last
end
end
and the index.html.erb
<h1>Hello World!</h1>
<h2>Posts</h2>
<% @posts.each do |post| %>
<h3><%= link_to post.title, post %></h3>
<p><%= post.content %></p>
<%= latestComment = post.latestComment(post) %>
<% end %>
<h3>Add new post</h3>
<%= link_to "Add new post", new_post_path %>
This works, it returns some hexa values, so the object exists, however then I now want to get fields from that object like this
<p><%= latestComment.author %></p>
<p><%= latestComment.content %></p>
It fails and the error is
undefined method `author' for nil:NilClass
which is weird and I dont get it why cant I access comments fields..
///comment.rb
class Comment < ActiveRecord::Base
attr_accessible :author, :content, :post_id
belongs_to :post
end
Upvotes: 1
Views: 1536
Reputation: 29941
Since you are looping over multiple posts, it's possible that one of them doesn't have any comments, which makes post.comments.last
return nil. You can work around this by checking it before trying to render the comment:
class Post < ActiveRecord::Base
def has_comments?
comments.count > 0
end
def last_comment
comments.last
end
end
Then, on the view:
<% @posts.each do |post| %>
<h3><%= link_to post.title, post %></h3>
<p><%= post.content %></p>
<% if post.has_comments? %>
<p><%= post.last_comment.author %></p>
<p><%= post.last_comment.content %></p>
<% end %>
<% end %>
Upvotes: 2