簡體   English   中英

Active Storage無法使用AJAX Rails 5.2上傳圖像附件

[英]Active Storage failing to upload image attachment with AJAX Rails 5.2

我收到Module :: DelagationError(大小委托給附件,但附件為零):在使用Active Storage發布基於AJAX的表單時,我的posts_controller.rb中的create方法。 如何修復我的代碼以允許Active Storage在AJAX創建的容器中創建帶有圖片的帖子?

post.rb

has_one_attached :photo

posts_controller.rb

  def create
    @post = current_user.posts.build(post_params)
    respond_to do |format|
      if @post.save
        format.js
        format.html {redirect_to post_path}
      end
    end
  end


   # Never trust parameters from the scary internet, only allow the white list through.

  def post_params
    params.require(:post).permit(:body_text, :photo, :user_id, :post_id)
  end

post / _form.html.erb

<%= simple_form_for(@post, html: {multipart: true}, remote: true, authenticity_token: true) do |f| %>
  <%= f.error_notification %>
  <div class="row">
    <div class="col">
      <div class="-textarea">
      <%= f.input :body_text, as: :text, class: 'form-control post-placeholder post-txt-area', label: false, placeholder: 'Write a post', style: "overflow: hidden; resize: none;", input_html: {:maxlength => 100, data: {:'meteor-emoji' => 'true'}}  %>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-5">
      <%= f.button :submit, 'Post', class: 'form-control submit-button bttn-gradient bttn-md bttn-royal', :data => {:disable_with => 'Posting .'} %>
  </div>
 <div class="col-md-5">
  <label class="bttn-minimal bttn-md bttn-red">
    Add Photo
    <span style="display:none;">
            <%= f.input :photo, as: :file, label: false, input_html: {accept: 'image/*'} %>
            </span>
  </label>
  <% if f.object.photo.attached? %>
    <%= image_tag(url_for(f.object.photo), class: 'img-responsive img-thumbnail') %>
  <% end %>
  <div class="preview-container">
    <img id="img_prev" width="100" height="100" src="#" alt="preview" class="img-thumbnail d-none"/> <br/>
    <a href="#" id="cancel_img_btn" class="d-none" onclick="return !(document.getElementById('post_photo').innerHTML=document.getElementById('post_photo').innerHTML);">Cancel
      Upload</a>
      </div>
    </div>
  </div>
<% end %>

服務器開發日志

Processing by PostsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"yiPHWZDBoFZOxLyNh8AphWOX5regegegeRXVGtz7mFeMdA/ZKAiiaCYjpJ/UOQ0n820gK0m5ZoKpFd483QFt+bnFDgGrLA==", "post"=>{"body_text"=>"oook!"}, "commit"=>"Post"}
  User Load (2.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 
ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (1.0ms)  BEGIN
   (0.0ms)  ROLLBACK
Completed 500 Internal Server Error in 9ms (ActiveRecord: 3.0ms)



Module::DelegationError (size delegated to attachment, but attachment is nil):

您不能使用Ajax發送文件。

現在所有瀏覽器都可以使用。

但是您可以使用可以執行hack的寶石“ remotipart”,並且行為類似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM