Hi to all. I’ve a very big problem. I know this can seem very loing, but
please, try to read it. I have a simply blog, with posts and their
comments. I’ve two tables in my db, posts, with post id, text and
comments_count to store the number of comments-children of each post (as
recomanded to do in AWDWR); and the table comments, with comment id,
post_id for the post they’re referred to, and text (there are many other
fields, but they’re not importat here). I have a home_controller, this
is the code:
class HomeController < ApplicationController
def index
@posts = Post.find(:all, :order => "data DESC")
end
def show_comment
@posts = Post.find(:all, :order => "data DESC")
@comments = Comment.find(:all, :conditions => ['post_id= ?',
params[:id] ])
end
def add_comment
@posts = Post.find(:all, :order => "data DESC")
@comments = Comment.find(:all, :conditions => ['post_id= ?',
params[:id] ])
@com = Comment.new(:post_id => params[:post_id])
if flash[:comment]
@comment = flash[:comment]
else
@comment = Comment.new
end
end
def save_comment
if request.post?
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Commento inserito con successo"
redirect_to("/home/show_comment/" +
params[:comment][:post_id])
else
flash[:comment] = @comment
redirect_to("/home/add_comment/" + params[:comment][:post_id])
end
end
end
end
and three views, index, add_comment and show_comment.
The problem arise with add_comment. When i want to add a comment for a
post without any comment (i’m the first to insert a comment for a post),
it displays:
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.post_idExtracted source (around line #17):
14:
15: <% end %>
16: <% end %>
17: <%= com.post_id %>
18: <% if @com.post_id == post.id %>
19: <%= error_messages_for :comment %>
20: <% form_for @comment, :url => {:action => :save_comment} do |form| %>
This is the code for the add_comment page
<% for post in @posts %>
<div class="post">
<p>Titolo: <%= post.titolo %> <span>data: <%= post.data
%>
Testo:
<%= post.testo %>
<%= link_to ‘Commenti(’ + post.comments.size.to_s + ‘)’,
:action => ‘show_comment’, :id => post %>
<%= link_to ‘Aggiungi un commento’, :action =>
‘add_comment’, :id => post %>
<% for com in @comments %>
<% if com.post_id == post.id %>
<%= com.testo %>
<% end %>
<% end %>
<% if com.post_id == post.id %>
<%= error_messages_for :comment %>
<% form_for @comment, :url => {:action =>
:save_comment} do |form| %>
Autore:
<%= form.text_field :autore%>
Testo:
<%= form.text_area :testo %>
<%= form.hidden_field :post_id, :value =>
post.id %>
<%= submit_tag “Invia commento” , :class =>
“submit” %>
<% end %>
<%end%>
</div> <!-- post -->
<% end %>
PLEASE HELP ME to solve this problem!