Rails 3 - Unable to create a new post while at the SHOW view of another Post

一笑奈何 提交于 2019-12-12 02:06:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6823812/rails-3-unable-to-create-a-new-post-while-at-the-show-view-of-another-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!