composite-primary-keys / composite_primary_keys

Composite Primary Keys support for Active Record
1.03k stars 350 forks source link

ActiveStorage Support? #582

Open berniechiu opened 2 years ago

berniechiu commented 2 years ago

Hi @cfis, thanks for the nice gem.

Currently we have a simple setup

class Rating < RivoApplicationRecord
  self.primary_keys = :id, :shop_id

  has_many_attached :images
  ...
end

Basically ActiveStorage polymorphic table only supports one primary id under record_id for storage, but that's fine. We would just want to continue to record the :id instead of [:id, :shop_id]

At the moment, the fetching looks fine

# Rails Console
rating = Rating.first
rating.images.first
# ActiveStorage::Attachment Load (1.5ms) 
# SELECT "active_storage_attachments".* FROM "active_storage_attachments"
# WHERE "active_storage_attachments"."record_id" = 1 AND "active_storage_attachments"."record_type" = 'Rating' 
# AND "active_storage_attachments"."name" = 'images' ORDER BY "active_storage_attachments"."id" ASC LIMIT 1
Screen Shot 2022-10-10 at 6 23 49 PM

However, the attach action can't seem to grep any :id correctly.

rating.images.attach(io: Down.download(url), filename: "test1")

#  ActiveStorage::Attachment Create (2.1ms)  INSERT INTO "active_storage_attachments" ("name", "record_type", "record_id", "blob_id", "created_at")
# VALUES ('images', 'Rating', NULL, 16, '2022-10-10 07:59:35.600141') RETURNING "id"

# ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR:  null value in column "record_id" violates not-null constraint

Thanks for you help!

cfis commented 2 years ago

Hmm, sorry, haven't ever used ActiveStorage. Happy to take a patch if you want to work out a fix.