Skip to content

Instantly share code, notes, and snippets.

@pgwillia
Created July 28, 2021 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgwillia/8b8e0996007db4177a5e962384d18c8f to your computer and use it in GitHub Desktop.
Save pgwillia/8b8e0996007db4177a5e962384d18c8f to your computer and use it in GitHub Desktop.
Validation of an attached ActiveStorage file

Problem:

I have an object that has a csv file attached using ActiveStorage.

I'm going to do some operations based on the content of that csv file so I want to validate that the file I'm attaching has the information I will need.

So the class looks something like this:

class MySpreadsheet < ApplicationRecord
  has_one_attached :csvfile

  validate :spreadsheet_has_required_data

  def spreadsheet_has_required_data
    csvfile.open do |file|  # .open triggers an ActiveStorage::FileNotFoundError error
     ...
    end
  end

Turns out that this is the intended behaviour.

Others have had my same problem: rails/rails#36994

Solution:

Is a bit of a hack, but you can find the tmp location of the attached file and use it in the validation.

  def spreadsheet_has_required_data
    file_path = attachment_changes['csvfile'].attachable[:io].path
    ...
  end

rails/rails#36994 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment