【发布时间】:2019-03-14 19:29:48
【问题描述】:
当使用 Active Storage 发布基于 AJAX 的表单时,我收到 Module::DelagationError(大小委托给附件,但附件为零):用于我的 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):
【问题讨论】:
-
你对
post_params的定义是什么? -
这可能是因为我的模型上定义了列。我会再试一次并更新问题正文。
-
我更新了问题正文。
-
我从帖子表中删除了 :photo 列。尽管如此,我还是无法通过 create 方法。
-
它可能是用于主动存储的 file_validators gem
标签: javascript ruby-on-rails ruby ajax rails-activestorage