【发布时间】:2019-04-10 23:44:35
【问题描述】:
在将我的应用程序升级到 Rails 5.2 后,我找到了一些时间来研究 Active Storage。按照指南,我已经安装并运行了必要的迁移。
在我的用户模型上,我想按照此处的示例附加一个头像:Edge Guide for Active Storage
我在提交表单时收到的错误是ActionController::InvalidAuthenticityToken
<%= form_for @user, remote: true do |f| %>
<%# Other user fields redacted %>
<div class="form-group">
<%= f.label :avatar %>
<%= f.file_field :avatar %>
</div>
<%= f.submit "Save", remote: true %>
<% end %>
我将 form_for 更改为包含 authenticity_token: true,如下所示:
<%= form_for @user, remote: true, authenticity_token: true do |f| %>
这消除了我的真实性错误并将文件插入到我的数据库中,但这导致了未知格式错误,因为它使用 html 而不是 js 路由到我的控制器。
日志:
Started PATCH "/users/22" for 127.0.0.1 at 2018-11-07 13:36:22 +0000
Processing by UsersController#update as HTML
Disk Storage (5.7ms) Uploaded file to key: aJQ3m2skk8zkHguqvhjV6tNk (checksum: 7w6T1YJX2LNIU9oPxG038w==)
ActiveStorage::Blob Create (23.6ms) INSERT INTO `active_storage_blobs` (`key`, `filename`, `content_type`, `metadata`, `byte_size`, `checksum`, `created_at`) VALUES ('aJQ3m2skk8zkHguqvhjV6tNk', 'Dq3gtJjU0AAbdIj.jpg-large.jpeg', 'image/jpeg', '{\"identified\":true}', 50642, '7w6T1YJX2LNIU9oPxG038w==', '2018-11-07 13:36:22')
ActiveStorage::Attachment Create (3.4ms) INSERT INTO `active_storage_attachments` (`name`, `record_type`, `record_id`, `blob_id`, `created_at`) VALUES ('avatar', 'User', 22, 1, '2018-11-07 13:36:22')
(9.4ms) ROLLBACK
Completed 406 Not Acceptable in 630ms (ActiveRecord: 93.1ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
用户#更新
def update
respond_to do |format|
if @user.update(user_params)
flash.now[:notice] = 'User saved successfully!'
format.js do
@users = User.all
end
else
flash.now[:alert] = @user.errors.full_messages.to_sentence
format.js do
@users = User.all
render layout: false, content_type: 'text/javascript'
end
end
end
end
关于为什么它被提交为 HTML 而不是 JS 的任何想法?
编辑:表单标记
<form class="edit_user" id="edit_user_22" enctype="multipart/form-data" action="/users/22" accept-charset="UTF-8" data-remote="true" method="post">
【问题讨论】:
-
您检查过表单标记吗?你能验证表单属性上确实有
data-remote="true"吗? -
是的,已将此添加到我的帖子中。只是补充一下 - 在我向其中添加活动存储之前,此表单运行良好。
-
您的表单正在使用 POST 方法。尝试将
method: :patch添加到您的form_for标签 -
您可以在提交按钮上删除
remote: true并重试吗?当在你的表单中将 remote 设置为 true 时,它总是运行到 update.js.erb 文件。不需要 format.js 做... -
@NMPennypacker - 添加
method: :patch仍然会在表单标记中产生method="post"。在我的浏览器中将其更改为method="patch"会导致表单尝试提交到显示操作! @Dapeng114 - 不幸的是,从提交按钮中删除 remote: true 得到了相同的结果。感谢您提供有关 format.js 的提示!
标签: ruby-on-rails rails-activestorage