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 :photosassociation in yourLocationmodel is properly configured. - Your controller’s
attach_photoaction 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_photois 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

