rails icon indicating copy to clipboard operation
rails copied to clipboard

Rails 7.1 attached image raises error because "Cannot get a signed_id for a new record" in image_tag

Open gregorbg opened this issue 5 months ago • 5 comments

Steps to reproduce

Say I have a model with an attached image, like such:

class Company < ApplicationRecord
  has_one_attached :logo
  
  validates :name, presence: true
end

...and there is also a controller to update it using the route defined by resources :companies like such:

def update
  @company = Company.find(params[:id])
  company_params = params.require(:company).permit(:name, :logo)

  if @company.update(company_params)
    flash[:success] = "Successfully updated Company!"
    redirect_to edit_company_path(@company)
  else
    render :edit
  end
end

The edit form is an HTML form that looks as follows:

<%= simple_form_for @company, url: edit_company_path(@company) do |f| %>
  <%= f.input :name %>
  <%= f.input :logo %>
  <% if @company.logo.attached? %>
    <%= image_tag @company.logo.variant(resize: "200x200") %>
  <% end %>
<% end %>

Now when I pass in an update payload that generates an invalid state (as per my Company model's validations) but has a valid, existing, readable logo file, the following error occurs:

ActionView::Template::Error: Cannot get a signed_id for a new record

Failure/Error: <%= image_tag @company.logo.variant(resize: "200x200") %>

     ActionView::Template::Error:
       Cannot get a signed_id for a new record

This is because the @company.update(...) statement in the controller writes the attributes, but the actual raw saving to the database fails because of validations.

The edit form then tries to display the new, updated but not persisted logo in the frontend, which raises the error about signed_id.

Expected behavior

The edit form should render, with the form showing errors on the name field according to the validators of the company model. Uploading a correct, readable logo should not cause the form to throw an error when rendering.

Actual behavior

The error above is being thrown.

System configuration

Rails version: 7.1.2

Ruby version: 3.2.2

gregorbg avatar Dec 01 '23 17:12 gregorbg