In the browser address bar i have http://localhost:3000/comment/index?post_id=6, i can access the post_id in the index,but when trying to create comment/post in the create action, it says couldnt find post without post ID in the log.What is going on here?thank you in advance.
Comments controller:
def index
@post=Post.find(params[:post_id])
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.save
respond_with( @comment, :layout => !request.xhr? )
end
comments/index view:
<%= form_for :comment, :remote => true,
:url => { :controller => "comments",
:action => "create"
},
:html => { :id => 'new-comment'} do |f|
%>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.text_area :body %>
<%= f.submit "post" %>
<% end %>
In the log:
Started POST "/comments" for 127.0.0.1 at 2011-10-17 14:06:36 -0700
Processing by CommentsController#create as JS
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"cxQm2K2xwsyw0DY2XLNvkcMQI+wM96LpEENbfQqxu5c=",
"comment"=> {"post_id"=>"6", "body"=>"This is the comment"},
"commit"=>"post"}
Completed 404 Not Found in 23ms
ActiveRecord::RecordNotFound (Couldn't find Post without an ID):
If you take a look in the params hash in your log, you’ll see this:
So the post ID is there, but it’s inside the
commenthash. So, in your create action, you just need to change to:However, you should be able to simplify the create action a bit.
Since the
post_idis in thecommentparams, the comment will automatically be associated with the post when you create it, without having to look up the record. If you need to access the post in your view, you can use@comment.post.