RoR InvalidAuthenticityToken 与 Active Storage 直接上传

RoR InvalidAuthenticityToken with Active Storage direct upload

我正在尝试使用 rails 活动存储直接上传到 Amazon s3 存储桶。但是,当存储介质是本地磁盘时,就当成直接上传吧,因为我也弄不通。

如果没有 ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): 错误,我将无法执行此操作。

我完全遵循了这个指南:https://guides.rubyonrails.org/active_storage_overview.html#direct-uploads

我什至在 application_controller.rb skip_before_action :verify_authenticity_token

中用这行代码禁用了 csrf 应用程序

只有当我的表单中有 direct_upload: true 时才会发生这种情况。

这是我的表格:

<%= form_with url: messages_path do |form| %> <%= form.label 'Upload' %> <%= form.file_field :audio_message, class: 'form-control', direct_upload: true, :required => true%> <%= form.submit 'Upload file', class: 'form-control' %> <% end %>

看起来 ajax 提交没有提取令牌。您可以尝试以下任一方法:

  1. 告诉表格嵌入令牌<%= form_with url: messages_path, authenticity_token: true...%>

  2. 在配置中添加config.action_view.embed_authenticity_token_in_remote_forms = true

看看他们是否对你有帮助。我的猜测纯粹来自于:https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with