Nick Ginanto
Nick Ginanto

Reputation: 32120

Sending a form with remote true in Rails 4

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?

Upvotes: 7

Views: 12499

Answers (3)

Sandeep Kapil
Sandeep Kapil

Reputation: 992

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

Upvotes: 5

Philip7899
Philip7899

Reputation: 4677

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.

Upvotes: 8

ironsand
ironsand

Reputation: 15141

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

Upvotes: 2

Related Questions