Search code examples
ruby-on-railsdebuggingpolymorphismrails-activestorageirb

Simulating selecting a file for Active Storage in irb


Creating a new item for Active Storage.

<!-- app/views/docs/_form.html.erb -->
  <%= f.label :image, "Select document or image that support this information." %>
  <%= f.file_field  :image %>

I'm getting a Please review the problems below error when I click Create and thought I'd see what errors happen in irb. But how do I simulate the above step.

Models:

# models/doc.rb
class Doc < ApplicationRecord
  has_one_attached :image # Active Storage
  belongs_to :source
  belongs_to :docable, polymorphic: true

# models/source.rb
class Source < ApplicationRecord
  has_many :docs

# models/year.rb
class Year < ApplicationRecord
  belongs_to :location
  belongs_to :person
  has_many :docs, as: :docable

# models/person.rb
class Person < ApplicationRecord
  has_many :years, dependent: :destroy
  has_many :locations, through: :years
  has_many :docs, as: :docable

# models/location.rb
class Location < ApplicationRecord
  has_many :years
  has_many :people, through: :years
  has_many :docs, as: :docable

Where a person lived or worked at on a date is set in years. year, person and location use doc to show the reference for that information. The source is the title of an old book and I'm imaging various pages in the book. Later I refer to those images using docable (that's the plan).

db/structure.sql: CREATE INDEX index_docs_on_docable_type_and_docable_id ON public.docs USING btree (docable_type, docable_id);

Here's the session:

irb(main):100:0> doc = Doc.new
=> #<Doc id: nil, source_id: nil, page_no: nil, original_url: nil, basename: nil, created_at: nil, updated_at: nil, notes: nil, docable_id: nil, docable_type: nil>
irb(main):101:0> doc.save
=> false
irb(main):102:0> doc.errors.messages
=> {:source=>["must exist"], :docable=>["must exist"]}
 irb(main):104:0> doc.source_id = 4
=> 4
irb(main):105:0> doc.save
   (42.8ms)  BEGIN
  Source Load (45.3ms)  SELECT "sources".* FROM "sources" WHERE "sources"."id" = $1 LIMIT $2  [["id", 4], ["LIMIT", 1]]
   (0.2ms)  ROLLBACK
=> false
irb(main):106:0> doc.errors.messages
=> {:docable=>["must exist"]}
irb(main):107:0> doc.image =

I may have problems with the polymorphic relationship, so I'm trying to sort that out.


Solution

  • https://edgeguides.rubyonrails.org/active_storage_overview.html#attaching-file-io-objects

    doc.image.attach(io: File.open('/path/to/file'), filename: 'file.jpg')