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?
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_idURL style, as you can add further parameters, too:would result in
and in your action do:
and render your form…