You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails ActiveStorage报MessageVerifier无效签名错误,咨询附件添加方式是否正确

The ActiveSupport::MessageVerifier::InvalidSignature error you're encountering is almost certainly tied to a missing CSRF token in your form submission. Rails requires valid CSRF tokens for non-GET requests to block cross-site request forgery attacks, and your form_tag isn’t including this token by default.

First, let’s confirm: your core approach to attaching photos to a has_many_attached collection is correct:

  • The has_many_attached :photos association in your Location model is properly configured.
  • Your controller’s attach_photo action correctly fetches the location and uses @location.photos.attach(params[:photo]) to add the uploaded file to the collection.
  • The member route for post :attach_photo is set up correctly.

Now, let’s fix the CSRF issue with one of these two simple solutions:

Option 1: Add the CSRF token to your existing form_tag

Modify your form to explicitly include the authenticity token by passing the authenticity_token: true option:

<%= form_tag attach_photo_location_path(@location), authenticity_token: true do %>
  <%= label_tag :photo %>
  <%= file_field_tag :photo %>
  <%= submit_tag "Upload" %>
<% end %>

Alternatively, you can add the token as a hidden field manually:

<%= form_tag attach_photo_location_path(@location) do %>
  <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
  <%= label_tag :photo %>
  <%= file_field_tag :photo %>
  <%= submit_tag "Upload" %>
<% end %>

Option 2: Switch to form_with (Rails 5.1+)

form_with is the recommended form helper in modern Rails versions, and it automatically includes the CSRF token for same-origin requests. Here’s how your form would look:

<%= form_with url: attach_photo_location_path(@location), method: :post do %>
  <%= label_tag :photo %>
  <%= file_field_tag :photo %>
  <%= submit_tag "Upload" %>
<% end %>

Quick Additional Check

Ensure your application layout (usually app/views/layouts/application.html.erb) includes the CSRF meta tags in the <head> section:

<head>
  ...
  <%= csrf_meta_tags %>
  ...
</head>

Once you add the CSRF token to your form, the InvalidSignature error should disappear, and your photo attachment workflow will work as intended.

内容的提问来源于stack exchange,提问作者simonlehmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:42:57