【问题标题】:Sending a form with remote true in Rails 4在 Rails 4 中发送带有远程 true 的表单
【发布时间】:2014-03-07 21:48:09
【问题描述】:

我有一个用于更新图像的表单

<%= form_for current_user, url: update_image_user_path(current_user), method: :post, html: {multipart: :true, remote: true},  :authenticity_token => true do |f| %>

动作有

respond_to do |format|
        format.js
        format.html
    end

但我收到以下错误

ActionView::MissingTemplate - Missing template users/update_image, application/update_image with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}.

我没有 update_image.html.erb 模板,但是从错误中我了解到请求不是以 js 格式发送的

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ajax forms ruby-on-rails-4


    【解决方案1】:

    有几件事你应该知道。

    1. Ajax 使用称为 xmlhttprequest 的东西来发送数据。不幸的是,xmlhttprequests 不能发布文件。 Remotipart 可能有效,但在 jqueryfileupload 上还有更多文档,以及 rails cast 视频。它被许多网站使用(很多甚至不使用rails)。我建议将 jqueryfileupload-rails gem 与 rails cast 一起使用:

      A. https://github.com/tors/jquery-fileupload-rails
      B. http://railscasts.com/episodes/381-jquery-file-upload

    2. remote: true 不是 html 属性。更改您的代码:

      <%= form_for current_user, url: update_image_user_path(current_user), 
          method: :post, html: {multipart: :true}, remote: true,  
          :authenticity_token => true do |f| %>
      

    您遇到的错误中最重要的部分是:

    :formats=>[:html]
    

    应该说:

    :formats=>[:js]
    

    现在在正确的位置使用 remote:true,错误应该会消失。

    【讨论】:

    • 这应该是公认的答案。你的第二种方法对我来说很好。非常感谢@Philip7899
    【解决方案2】:

    rails remote true 不适用于图片上传。您不能仅使用远程 true 上传带有 ajax 的图像。你需要 jquery.form.js 文件给用户 ajaxForm。为此包括

        <script src="http://malsup.github.com/jquery.form.js"></script>
    

    并绑定表单

         $("#formid").ajaxForm()
    

    或者你可以使用 jqueryfileupload-rails gem

    https://github.com/tors/jquery-fileupload-rails

    【讨论】:

      【解决方案3】:

      html: {multipart: :true}, remote: true 而不是html: {multipart: :true, remote: true} 怎么样?

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多