create model with active storage attachment pass, not a hash

Rails 5.2

I want to pass a object that responds to the right method so I do not have to pass a hash of the keys/values to create a model with an active storage attachment.

what I want

Painting.create!(image: art) 

instead of doing,

Painting.create!(image: art.as_hash)

or,

Painting.create!(image: { io: "data", content_type: "image/png", filename: "Moon Ape" }) 

I have tried

class Art
  def [](key)
    { io: "data", content_type: "image/png", filename: "Moon Ape" }[key]
  end
end

obviously

class Art
  def as_hash
    { io: "data", content_type: "image/png", filename: "Moon Ape" }[key]
  end
end

works

This has to be possible because you can do it from the controller via sudo code:

params = ActionController::Parameters {"image"=>. <ActionDispatch::Http::UploadedFile:0x00007fb5c63f7220 @tempfile=......

 Painting.create!(params)

I looked ActionDispatch::Http::UploadedFile does not seem to respond to anything that made sense.



Read more here: https://stackoverflow.com/questions/68474963/create-model-with-active-storage-attachment-pass-not-a-hash

Content Attribution

This content was originally published by ChrisCPO at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: