Rails file_field does not upload anything

2019-02-26 01:38发布

问题:

I am using Rails 4 and Ruby 2 with Carrier Wave along with jQuery Mobile 1.3, and a user has a profile which has a logo. I have tested the backend Carrier Wave stuff in the console and it works.

The problem is in the form helper, it doesn't matter what I do, but a file_field will display and let me choose an image, but it does not come through in the params. If I change it to a field that does not exist eg. =f.file_field :field_not_permitted_in_strong_params it does not fall over and a file picker is visible, if I change that to =f.text_field :field_not_permitted_in_strong_params, only then does rails kick in and complain about the field not existing.

So my problem is basically, I can upload a file client side, but it does not get sent through in the form data, or appear in the params hash, and all my other fields work correctly.

Here is a snippet of the form:

= form_for(@business_profile, :html => {:multipart => true}, :url => business_profile_path, :validate => true) do |f|

    =image_tag(@business_profile.logo.url, class: 'business-logo')
    %div{:data => {:role => 'fieldcontain'}}
        =f.file_field :logo

    - # Basic Information
    %div{:data => {:role => 'collapsible', :collapsed => 'false'}}
        %h3
            Basic Information                 
        %div{:data => {:role => 'fieldcontain'}}
            = f.label :name, 'Business name:' 
            = f.text_field :name
        %div{:data => {:role => 'fieldcontain'}}
            = f.label :address, 'Address:'
        = f.text_area :address, class: 'address'

回答1:

OK after spending hours on the matter, the problem is that jQuery Mobile submits forms with Ajax by default, and files cannnot be submitted with Ajax without using plugins etc. So the solution is to disable the Ajax like this:

= form_for(@business_profile, :url => business_profile_path, :validate => true, :html => { :'data-ajax' => false }) do |f|