AJAX渲染弄乱了我的路线 [英] AJAX rendering is messing up my routes

查看:77
本文介绍了AJAX渲染弄乱了我的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制者杂志和文章,文章是杂志的嵌套路线。当我进入 / magazines / show 时,有一种创建文章的基本形式

I have two controllers magazines and articles, articles is a nested route of magazines. When I'm in /magazines/show there's a basic form to create an article

<%= form_for @article, :url => magazine_articles_path(@magazine), remote: true do |f| %>
    <%= render 'shared/error_messages', target: @article %>
    <%= f.text_field :name %>
    <%= f.submit %>
<% end %>

提交时,它将发送到Articles控制器。在articles控制器中,我呈现了一个重新呈现此表单的操作(我正在重新呈现该表单以消除存在的错误)

When this submits it gets sent to the articles controller. In the articles controller I render an action that rerenders this form (I'm rerendering the form to get rid of the errors if there are any)

$('#id').html('<%= escape_javascript render partial: 'create_article' %>');

但这会将表单的操作更改为 / magazines /:id / articles 代替 / magazines /:id

This however changes the form's action to /magazines/:id/articles instead of /magazines/:id

初始形式:

<form id="new_article" class="new_article" method="post" data-remote="true" action="/magazines/1/articles" accept-charset="UTF-8">

重新渲染后的表格:

<form id="edit_article_3" class="edit_article" method="post" data-remote="true" action="/magazines/1/articles" accept-charset="UTF-8">

如果我尝试再次提交此表单,则会弄乱我的路由,并给我路由错误。我猜这是因为新的 @article 来自商品控制器。我们将非常感谢您提供有关此情况如何发生的详细信息以及解决该问题的清晰解决方案。谢谢!

This messes up my routing and gives me routing errors if I try to submit this form again. I'm guessing this is occuring because the new @article is coming from the articles controller. A little more detail of how this happens and a clean solution to get around it would be much appreciated. Thanks a bunch!

推荐答案

哈!在第二种情况下,您的 @article 已经存在,并且您的表单应如下所示:

Ha! In the second case your @article already exists, and your form should look as follows:

<%= form_for @article, :url => magazine_articles_path(@magazine, @article), remote: true do |f| %>

所以要多解释一下:由于 @article 存在,则应明确说明正在编辑哪个 @article 。如果尚不存在该文章,则只需创建一个新文章即可。

So to explain it more: since the @article exists, you should make it clear which @article is being edited. If the article does not exist yet, it just needs to create the new article.

路径助手可以处理新记录,也可以处理现有记录本身,否则,您将不得不执行以下操作

It is possible that the path-helper can handle new records vs. exisiting records itself, otherwise you will have to do something like

<% post_url = @article.new_record? ? magazine_articles_path(@magazine) : magazine_articles_path(@magazine, @article) %>
<%= form_for @article, :url => post_url, remote: true do |f| %>

希望这会有所帮助。

这篇关于AJAX渲染弄乱了我的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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