AJAX rendering is messing up my routes

假如想象 提交于 2019-12-12 02:12:37

问题


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

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' %>');

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

Initial Form:

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

Form after rerendering:

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

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!


回答1:


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

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

Hope this helps.



来源:https://stackoverflow.com/questions/11280070/ajax-rendering-is-messing-up-my-routes

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