【发布时间】:2020-11-04 08:21:42
【问题描述】:
我有一个由 Rails API 支持的 React 前端,我通过 Active Storage 将照片发送到 Cloudinary。我的设置是标准的:我有一个带有 has_one_attached :photo 方法的 Event 模型,而 POST 端点“/api/v1/events”由带有简单 @event = Event.new(event_params) 的“Events#create”方法提供服务。我还在“事件”表中保存了一个额外的“url”列,以便在需要时将其显示回来(我用@event.photo.url 得到它(警告说“service_url”据说已贬值)。我可以获取它(浏览器的 fetch api)并在 React 中使用它。这行得通。
当我编辑表单并使用新照片提交表单时,我必须使用以下 events#update 方法调整 PATCH 查询。我按照 Rails 指南说你应该 purge 和 create_and_upload!。
def update
@event = Event.find(params[:id])
logger.debug "..................BEFORE : ..#{@event.to_json}"
if event_params[:photo] || @event.url
@event.photo.purge
@event.url = nil
end
if @event.update(event_params)
if event_params[:photo]
ActiveStorage::Blob.create_and_upload!(
io: File.open(event_params[:photo].tempfile),
filename: event_params[:photo].original_filename,
content_type:event_params[:photo].content_type
)
@event.url = @event.photo.url
end
logger.debug "................AFTER :.. #{@event.to_json}"
render json: {status: :ok}
else
render json: {errors: @event.errors.full_messages},
status: :unprocessable_entity, notice:"not authorized"
end
end
我的日志显示这会产生一个 url,但没有 url 发送到 React。如果我修改此表单中的其他字段,我会从 Rails 中获取 React 中的更新。但是,未发送链接:url: null。
我什至不使用 Active Job,但使用 6.03 甚至更新到 6.1。有人经历过吗?
FI,params 哈希包含以下内容:
"photo"=>#<ActionDispatch::Http::UploadedFile:0x00007fd938f1ecf8 @tempfile=#<Tempfile:/var/folders/11/whcyvzvx3w54zb0n1r0929200000gn/T/RackMultipart20200714-79173-t9s624.svg>, @original_filename="Rafting.svg", @content_type="image/svg+xml", @headers="Content-Disposition: form-data; name=\"event[photo]\"; filename=\"Rafting.svg\"\r\nContent-Type: image/svg+xml\r\n">}
【问题讨论】:
标签: ruby-on-rails reactjs