form_for - Child object - how to set parent id

D L wrote:

So you can see I have a form for block to handle the comments entry -
but if I have multiple blogs on a single page how can I specify that
this particular comment relates to blog X? If I only have one blog per
page I can get away with storing the blog id in the session, but this
seems a bit messy.

Hi D L,

(Welcome to Rails, by the way).

The key is to learn about how to specify the relationships between your
models. In your comment model, indicate that it's parent object is a
Blog:

class Comment < ActiveRecord::Base
...
belongs_to :blog

end

Now, anytime you have a Comment object, you can use comment.blog to
"get back" to the parent blog object.

Does this help? If I misunderstood the question somehow, let me know.

Jeff
www.softiesonrails.com

Have you thought about using Ajax to create the form on the fly, thereby
making the ownership of the comment clearer?

D L-3 wrote:

> The problem is that I can not see any way to set the BlogId (parent) on
> the comment. So I have code in my controller that looks like this:
>
> def add_comment
> @comment = Comment.new(params[:comment])
> @comment.blog_id = ??? <- Where do I get this from???
> if @comment.save
> flash[:notice] = "Thank you for your comment"
> end
> list
> render :action => 'list'
> end
>

From your view code I assume that you create one blank comment in your
controller and are trying to reuse that?

A better way may be to add a new_comment method to the blog model:

def new_comment
  Comment.new( :blog=>self )
end

and then use

<%= form_for :comment, blog.new_comment, :url=>... %>
<%= form.hidden_field :blog_id %>

If you want to stick with the one-template-comment approach, do something like

<%= hidden_field :comment, :blog_id, :value=>blog.id %>

Cheers,
Max