我想我缺少明显的东西。
应该发生什么:
当用户将图片添加到Story#new表单时:
- 用户点击
file_field
Story#new
部分中的_form
: - JavaScript使用XMLHttpRequest将表单数据(包括包含图像的
file_field
)发布到自定义控制器操作中 - 该自定义操作使用activeStorage将该图像附加到关联的报表
- 该自定义操作会调用一个
.js.erb
视图,该视图会重新呈现部分视图 - 重新渲染的部分显示了已附加的图像
实际发生的事情
所有内容,但#5。
设置:
- 路轨6
- activeStorage
- Haml
- 咖啡
相关模型:
class Story < ApplicationRecord
belongs_to :report,inverse_of: :story
has_one_attached :image,dependent: :purge
def picture
image.attached? ? Rails.application.routes.url_helpers.rails_blob_path(image,only_path: true) :
actionController::Base.helpers.asset_path('story_no_image.png')
end
end
class Report < ApplicationRecord
has_one :story,inverse_of: :report,dependent: :destroy
has_one_attached :image,only_path: true) :
actionController::Base.helpers.asset_path('story_no_image.png')
end
end
根据现有报告创建故事。因此,要“热切预览”用户想要与故事关联的图像,让我们暂时将其保存到相关报告中。
步骤:
1。用户点击file_field
Story#new
部分中的_form
:
# app/views/stories/_form.haml
# @story is new,but it's associated @report already exists,# so let's temporarily associate the image with @report until @story gets created.
.container
.col-12
%h1 New Story
%h4= "For Report ##{link_to(@report.id,@report)} #{@report.details}".html_safe
.col-12
= simple_form_for @story,wrapper: :horizontal_form,html: { id: 'story_form' } do |f|
= f.input :report_id #,as: :hidden
.field
= f.input :title
.field.wysiwyg
= f.input :text,input_html: { class: "tinymce",style: "height: 300px;" }
.field
= f.label @story.image.present? ? 'Replace Picture:' : 'Choose Picture:'
= f.file_field :image,id: "image_upload",accept: 'image/*'
.actions
= f.submit 'Save',class: 'btn yellow'
.row.mt-5
.col-12
%h5 Image Preview:
.col-6#image_preview_wrapper
= render partial: 'image_preview',locals: { record: @story }
.col-6.text-center
=link_to 'Rotate Left','#',class: 'rotate-btn',data: { rotation: 'left' }
=link_to 'Rotate Right',data: { rotation: 'right' }
=link_to 'Delete Image',id: 'purge_img_btn'
= tinymce
# app/views/stories/_image_preview.haml
- byebug if record.class.name == 'Report' # using this debugger to make sure item #4 is actually happening
=image_tag(record.picture,id: "image_preview",class: 'yay!')
2。 Javascript发布表单数据
$(document).on 'turbolinks:load',->
# only for new records:
if controllerMatches(['stories']) and actionmatches(['new','create'])
$('#image_upload').on 'change',->
return unless !!$('#image_upload').val().length
reportId = $('#story_report_id').val()
eagerUrl = '/reports/' + reportId + '/upload_eager'
form = document.getElementById('story_form')
formData = new FormData(form)
xhr = new XMLHttpRequest()
xhr.open 'post',eagerUrl,true
xhr.send(formData)
自定义路由:
# routes.rb
resources :reports do
post 'upload_eager',on: :member
post 'rotate_eager',on: :member
end
3。该自定义操作使用activeStorage将该图像附加到关联的报表
# ReportsController
def upload_eager
# for Story#new,upload an 'eager' image by attaching the image
# to the report (which exists) instead of the story (which doesn't)
authorize @report = Report.find(params[:id])
return unless eager_image_params[:image].present?
# this method is my customization of @report.image.attach(image_io)
# so I can rename and resize the image before uploading.
@report.upload_image!(eager_image_params[:image]) unless @report.image.attached?
respond_to do |format|
format.js
end
end
4。该自定义操作将调用.js.erb
视图,该视图将重新呈现部分视图:
# upload_eager.js.erb
$('#image_preview_wrapper').html("<%= j render partial: 'stories/image_preview',locals: { record: @report } %>");
$('#image_preview').removeclass('boo');
$('#image_preview').addClass('YAY');
5。重新渲染的部分不不会显示附加的图像。
DOM不变(请注意,我在js部分中更改了标记的类)
- 我可以在Chrome DevTools中验证#1和#2是否正在发生(以及使用
ReportsController#upload_eager
中的调试器。 - 我看到#3和#4出现在终端日志中(也包括调试器和控制台gem)
- 我可以在任何地方使用
byebug
(调试器)并确认其工作正常,特别是@report
带有图像且路径正确。
但是浏览器视图没有更新。
我获得的唯一成功是:如果我从Network事件中获取upload_eager
JQuery的结果,请将其放在DevTools控制台中,然后按Enter,图像标签将被替换并且图像正确显示(又名-JQuery触发)。 / p>
这告诉我,来自partial的JQuery实际上并未触发,我可以确认,因为<img>
标记的类未更改。
让我感到困扰的是为什么终端日志向我显示了部分渲染:
Started POST "/reports/1615/upload_eager" for ::1 at 2019-11-21 23:09:16 -0500
Processing by ReportsController#upload_eager as */*
Parameters: {"utf8"=>"✓","authenticity_token"=>"H2SVzwB8b02wNde/YePpYnVGBYa3nd6i4THa21MLOQbNQ/CgE/lIjAqpqaCUnsCKzEEZCDuEGuLfylWwwreo9g==","story"=>{"report_id"=>"1615","title"=>"","prominent"=>"0","text"=>"","image"=>#<actionDispatch::Http::UploadedFile:0x00007fc2237425b0 @tempfile=#<Tempfile:/var/folders/th/fsmws2ns6t54j_yy1wbk7qhc0000gn/T/RackMultipart20191121-80561-1j4sec1.JPG>,@original_filename="test-story-family-sam3.JPG",@content_type="image/jpeg",@headers="Content-Disposition: form-data; name=\"story[image]\"; filename=\"test-story-family-sam3.JPG\"\r\nContent-Type: image/jpeg\r\n">},"year"=>"2019","month"=>"8","id"=>"1615"}
Report Load (0.3ms) SELECT "reports".* FROM "reports" WHERE "reports"."id" = $1 LIMIT $2 [["id",1615],["LIMIT",1]]
↳ app/controllers/reports_controller.rb:82:in `upload_eager'
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id",1],1]]
↳ app/controllers/reports_controller.rb:82:in `upload_eager'
Unpermitted parameters: :report_id,:title,:prominent,:text
activeStorage::Attachment Load (0.4ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id",["record_type","Report"],["name","image"],1]]
↳ app/controllers/reports_controller.rb:86:in `upload_eager'
Unpermitted parameters: :report_id,:text
(0.2ms) BEGIN
↳ app/models/report.rb:91:in `upload_image!'
Technology Load (0.4ms) SELECT "technologies".* FROM "technologies" WHERE "technologies"."id" = $1 LIMIT $2 [["id",1]]
↳ app/models/report.rb:91:in `upload_image!'
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id",2],1]]
↳ app/models/report.rb:91:in `upload_image!'
Contract Load (0.4ms) SELECT "contracts".* FROM "contracts" WHERE "contracts"."id" = $1 LIMIT $2 [["id",4],1]]
↳ app/models/report.rb:91:in `upload_image!'
Village Load (0.3ms) SELECT "villages".* FROM "villages" WHERE "villages"."id" = $1 LIMIT $2 [["id",3],1]]
↳ app/models/report.rb:91:in `upload_image!'
activeStorage::Blob Load (0.5ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" INNER JOIN "active_storage_attachments" ON "active_storage_blobs"."id" = "active_storage_attachments"."blob_id" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id",1]]
↳ app/models/report.rb:91:in `upload_image!'
activeStorage::Blob Create (0.4ms) INSERT INTO "active_storage_blobs" ("key","filename","content_type","metadata","byte_size","checksum","created_at") VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING "id" [["key","moe206b5grl9laccxf4707kfb5ma"],["filename","000000_eager_1615.JPG"],["content_type","image/jpeg"],["metadata","{\"identified\":true}"],["byte_size",108855],["checksum","9BB+x9JRqJfEKb+RKcUEFA=="],["created_at","2019-11-22 04:09:17.443238"]]
↳ app/models/report.rb:91:in `upload_image!'
activeStorage::Attachment Create (0.4ms) INSERT INTO "active_storage_attachments" ("name","record_type","record_id","blob_id",$5) RETURNING "id" [["name",["record_id",["blob_id",33],"2019-11-22 04:09:17.447089"]]
↳ app/models/report.rb:91:in `upload_image!'
(0.4ms) SELECT "plans"."id" FROM "plans" WHERE "plans"."contract_id" = $1 AND "plans"."technology_id" = $2 AND "plans"."planable_id" = $3 AND "plans"."planable_type" = $4 LIMIT $5 [["contract_id",["technology_id",["planable_id",["planable_type","Village"],1]]
↳ app/models/report.rb:274:in `find_plan'
Report Update (0.4ms) UPDATE "reports" SET "updated_at" = $1 WHERE "reports"."id" = $2 [["updated_at","2019-11-22 04:09:17.450861"],["id",1615]]
↳ app/models/report.rb:91:in `upload_image!'
(0.6ms) COMMIT
↳ app/models/report.rb:91:in `upload_image!'
Disk Storage (5.8ms) Uploaded file to key: moe206b5grl9laccxf4707kfb5ma (checksum: 9BB+x9JRqJfEKb+RKcUEFA==)
Rendering reports/upload_eager.js.erb
Rendered stories/_image_preview.haml (Duration: 1.0ms | Allocations: 310)
Rendered reports/upload_eager.js.erb (Duration: 3.7ms | Allocations: 840)
Completed 200 OK in 1227ms (Views: 6.9ms | activeRecord: 5.5ms | Allocations: 20005)