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!
Ha! In the second case your
@articlealready exists, and your form should look as follows:So to explain it more: since the
@articleexists, you should make it clear which@articleis 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
Hope this helps.