2017-02-14 38 views
0

В приложении «Мои рельсы» Мне нужно, чтобы пользователь мог публиковать сообщения в стиле Facebook, которые всегда содержат текст и необязательно изображение. Мне нужно, чтобы это произошло без перезагрузки страницы.Невозможно комбинировать нормальную форму с Dropzone.js

Поскольку я хотел бы использовать Dropzone.js для управления асинхронными загрузками изображений, я стараюсь совместить свою форму с Dropzone без успеха. Я использовал в основном this source.

Я немного потерялся здесь. То, что я пробовал, приведен ниже. Не могли бы вы указать мне в правильном направлении?

Моя форма здесь

<%= simple_form_for(@post, remote: true, :authenticity_token => true, html: { multipart: true, class: 'form-inline dropzone', id: 'new_post_form'}) do |f| %> 
     <div class="dropzone-previews"></div> 
     <%= f.input :content, :label => false, :placeholder => " Say something here!", as: :text, :required => true, :autofocus => true, :input_html => { id: "new_post_content_field" } %> 
     <%= f.input :poster_id, :as => :hidden, :required => true, :autofocus => true, input_html: {value: current_user.id } %> 
     <%= f.input :poster_type, :as => :hidden, :required => true, :autofocus => true, input_html: {value: current_user.class } %> 
     <%= f.input :community_id, :as => :hidden, :required => true, :autofocus => true, input_html: {value: @community.id } %> 
     <div class="fallback"> 
      <%= f.input :post_image, :label => false %> 
     </div> 
     <%= f.button :submit, input_html: {id: 'submit-all' } %> 
<% end %> 

Результирующий HTML

<form class="simple_form form-inline dropzone dz-clickable" id="new_post_form" novalidate="novalidate" enctype="multipart/form-data" action="/posts" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="3OC6YhVKtCvjXk0QIHQUUG+72PtkkN3NieWvtLmYzitsh2vDvhu2ggPJBcbDII+39CHuFaRqdRHXK27eR6W1Bw=="> 

     <div class="dropzone-previews"></div> 
     <div class="form-group text required post_content"><textarea class="form-control text required" id="new_post_content_field" autofocus="autofocus" required="required" aria-required="true" placeholder=" Say something here!" name="post[content]"></textarea></div> 
     <div class="form-group hidden post_poster_id"><input class="form-control hidden" value="2" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[poster_id]" id="post_poster_id"></div> 
     <div class="form-group hidden post_poster_type"><input class="form-control hidden" value="Participant" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[poster_type]" id="post_poster_type"></div> 
     <div class="form-group hidden post_community_id"><input class="form-control hidden" value="1" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[community_id]" id="post_community_id"></div> 

     <input type="submit" name="commit" value="Create Post" input_html="{:id=>&quot;submit-all&quot;}" class="btn btn-default" data-disable-with="Create Post"> 
<div class="dz-default dz-message"><span>Drop files here to upload</span></div></form> 

application.js

Dropzone.options.newPostForm = { 
    autoProcessQueue: false, 
    uploadMultiple: true, 
    parallelUploads: 100, 
    maxFiles: 100, 
    paramName: "post[post_image]", 


    init: function() { 
    var myDropzone = this; 

    $("#submit-all").click(function (e) { 
     e.preventDefault(); 
     e.stopPropagation(); 
     myDropzone.processQueue(); 
    }); 
    } 
} 

Создать действие в регуляторе сообщений

def create 
    @post = Post.new(post_params) 
    respond_to do |format| 
     if @post.save 
     @post_comment = Comment.new() 
     format.js 
     format.json { render json: { message: "success", fileID: @post.id }, :status => 200 } 
     else 
     format.js {render inline: "toastr.error('Something went wrong');"} 
     format.jsnon { render json: { error: @post.errors.full_messages.join(',')}, :status => 400 } 
     end 
     end 
    end 

В настоящее время, если я ударил «Отправить» я проточные Params

<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"3OC6YhVKtCvjXk0QIHQUUG+72PtkkN3NieWvtLmYzitsh2vDvhu2ggPJBcbDII+39CHuFaRqdRHXK27eR6W1Bw==", "post"=>{"content"=>"ddddddd", "poster_id"=>"2", "poster_type"=>"Participant", "community_id"=>"1"}, "commit"=>"Create Post", "controller"=>"posts", "action"=>"create"} permitted: false> 

Так что, кажется, нет Титулы, которые связаны с изображением не направляются в и я не уверен, как я могу это решить.

ответ

0

В итоге я выяснил, в чем проблема.

поле ввода для изображения (ниже) не должны были быть включены в виде помощника

<%= f.input :post_image, :label => false %> 

И я делал ошибку установки идентификатор кнопки отправки. Я использую:

<%= f.button :submit, input_html: {id: 'submit-all' } %> 

вместо:

<%= f.button :submit, id: 'submit-all' %> 

Это помешало JS, чтобы выбрать соответствующую кнопку формы.