0

I have a model named "Post". I want to use a modal form to create a new post while at the SHOW view of another post. Meaning while I am viewing the post named "John" in its show view, I would like to be able to create a new post from right there.

The problem I have is that the ID of the new post remains the same as the post I am viewing, and causes the update action to be fired instead of the create action. Any suggestions on how to handle this?

CJ Dennis
  • 4,226
  • 2
  • 40
  • 69
rgoraya
  • 241
  • 1
  • 3
  • 12

1 Answers1

3

Build a new post with Post.new and use that in a form_for:

<%= form_for Post.new %>
  <%= render "form" %>
<% end %>

Of course this means you'll need to remove the form_for from your form partial if you have it in there, but that's a small sacrifice to make.

However if you really don't want to do that then you will have to pass through a local variable to the form partial to indicate which post you want to display. On the show page you'd have this:

<%= render :partial => "form", :locals => { :post => Post.new } %>

In the new and edit views you'd do this:

<%= render :partial => "form", :locals => { :post => @post } %>

The line is a little bit longer, but that would allow you to keep the form_for tag inside the form partial and not clog up the three other views with it.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • Thanks a lot for quick response. However I did not understand this entirely. I tried this and (though no errors were thrown) the Post was not created. Also, I am using a Modal-Form and not aiming to redirect to _form partial to create a new Post. Could you please guide me. Thanks again! – rgoraya Jul 26 '11 at 00:10
  • Correction: It was unsuccessful due to my own mistake wherein I was redirecting this to the Index (based on the current submit action's name). Bottom line, question answered! Thanks Ryan. – rgoraya Jul 26 '11 at 00:26