Rails 3-在另一个帖子的SHOW视图中无法创建新帖子 [英] Rails 3 - Unable to create a new post while at the SHOW view of another Post

查看:58
本文介绍了Rails 3-在另一个帖子的SHOW视图中无法创建新帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Post的模型。我想在另一个帖子的SHOW视图中使用模式表格来创建新帖子。意思是,当我在其显示视图中查看名为 John的帖子时,我希望能够从那里创建一个新帖子。

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.

我遇到的问题是新帖子的ID与我正在查看的帖子相同,并导致触发更新操作而不是创建操作。有关如何处理此问题的任何建议?

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?

推荐答案

使用 Post.new 并在 form_for 中使用:

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

当然,这意味着您需要删除 form_for 从表单中分离出来(如果您有的话),但这是一个小小的牺牲。

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.

但是,如果您真的不想这样做您将必须通过局部变量将其传递给part部分,以指示要显示的帖子。在显示页面上,您将拥有以下内容:

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 } %>

该行稍长一些,但这可以让您保留 form_for 标记在表单部分内,而不阻塞其他三个视图。

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.

这篇关于Rails 3-在另一个帖子的SHOW视图中无法创建新帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆