Search code examples
ruby-on-railsajaxruby-on-rails-3.1form-forujs

Rails form_for with file_field and remote => true and format => :js


I am submitting a form_for with a file_field in it. When the form is submitted with a post, the controller responds with a .js file which will be executed.

The file_field is optional.

When I upload a file, the js file is opened in a new document (as a simple text file) and the js is not executed. When I don't upload any file, the response div is updated. I want the update success to be notified in the response div or a failure message independent of the file upload.

May be this is done for some security reasons? Is there some workaround for people who want to be able to do this?

Roughly,

Form partial _action.html.erb:

<div id="response"></div>
<%= form_for ... :remote => true, :url => {..., :format => :js} do |f| %>
    ...
    <%= f.file_field :name %>
<% end %>

Controller::action

 if not request.post?
    render :partial => 'controller/action'
    return
 else
    @response = "save was successful";
    # renders the action.js.erb
 end

action.js.erb:

$("#response").html("<%= @response %>");

Solution

  • Try to use remotipart gem https://github.com/JangoSteve/remotipart