Sending a form with remote true in Rails 4

2019-06-18 07:58发布

问题:

I have a form for updating an image with

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

the action has

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

but I am getting the following error

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

I don't have a update_image.html.erb template, but from the error I learn that the request isn't sent as js format

What am I missing?

回答1:

There are several things you should know.

  1. Ajax uses something called an xmlhttprequest to send your data. Unfortunately, xmlhttprequests cannot post files. Remotipart may work, but there is far much more documentation, plus a rails cast video, on jqueryfileupload. It is used by many sites (a lot that don't even use rails). I would suggest using the jqueryfileupload-rails gem along with the rails cast:

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

  2. remote: true is not an html attribute. Change your code tho:

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

The most important part of the error you are encountering is this:

:formats=>[:html]

That should say:

:formats=>[:js]

With remote:true in the right place now, the error should go away.



回答2:

rails remote true will not work for image upload. You can not upload image with ajax using only remote true. You need jquery.form.js file to user ajaxForm. For this include

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

and bind form

     $("#formid").ajaxForm()

Alternatively you can use jqueryfileupload-rails gem

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



回答3:

How about html: {multipart: :true}, remote: true instead of html: {multipart: :true, remote: true}?