views:

36

answers:

1

I have many instances of a Rails model, Post. When viewing an individual post, I'd like to create a form to create a child of Post called Comment. I'd like to prepopulate this form with a hidden tag that contains the post_id which is the foreign key in Comment.

The Railsy way to do this is to create a fancy-ish route such as:

/comments/new/post/:post_id

However, this gunks up the routes file and doesn't leave much flexibility. Let's say I want to create a link somewhere else that prepopulates a different attribute of the form...then I'd have to add another route for this.

So I think I'm going to create urls like this on /posts/show/:id:

/comments/new?comment[post_id]=<%= @post.id %>

This way I can add any other attributes as I need. I know the plus side associated with this, now what are the downsides?

+1  A: 

Just use new_comment_path :comment => { :post_id => @post.id } to create such URLs. You could wrap it into a helper if you'd like.

However, there should be no downside with the /comments/new/post/:post_id URL style, as you can add further parameters, too:

new_post_comment_path @post, :comment => { :additional => "parameters", ... }

would result in

/posts/:post_id/comments/new?comment[additional]=parameters&...

and in your action do:

def new
  @post = Post.find params[:post_id]
  @comment = @post.build params[:comment]
end

and render your form...

hurikhan77