rails ajax表单操作重写路由错误



我有一个rails应用程序,每次点击其中一个输入字段时,它都会进行连续保存。您从/posts/new开始。一旦你写了一些东西并点击了输入,表单就会通过ajax提交。/posts/new的表单属性随后更改为/post/1/edit的表单属性(1可以是任何数字)。并且,url被更新为/post/1/edit(同样,1可以是任何数字)。

当表单再次提交时,使用/post/1/edit和更新的表单属性,我会得到以下错误:

No route matches [POST] "/posts/4"

在谷歌铬控制台,我得到以下错误:

POST http://0.0.0.0:3000/posts/1 404 (Not Found)

这是我的密码。

/app/asset/javascripts/posts.js

$(document).ready(function() {
  $('.new_post').on('focusout', function(ev) {
    $('.new_post').submit();
  });
  $('.edit_post').on('focusout', function(ev) {
    $('.edit_post').submit();
  });
});

/app/controllers/post_controller.rb、/app/models/post.rb和/config/routes.rb是从post的scaffold生成的控制器、模型和路由。

app/views/posts/_form.html.erb

<%= form_for(@post, :remote => true) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

此外,还有一些事情。

1) 如果我只是去/post/1/edit,进行编辑并点击输入字段;不存在路由错误。

2) 表单操作posts/new的ajax更新后生成的html和post/1/edit页面生成的html是相同的。

如有任何帮助,我们将不胜感激。

谢谢。

您应该执行PUT来更新,代码正在执行POST请求,因此除非您包含_method:PUT,否则它不是可识别的路由。

最新更新