Rails and Shrine create model record with attachment

562 Views Asked by At

I need to upload image with Shrine using uploader, I have default uploader from example here including few derivatives.

Like here https://shrinerb.com/docs/getting-started

But I want to create new instance inside IRB, and I don't figure it out how to pass image properly to the Shrine. As I will finish it it will be used in a script for converting bunch of images.

If I do this:

Images.new(
  title: title,
  image: File.open("image.png")
)

It fails on validation because mime-type is empty. When I use form to upload image, there is ActionDispatch::Http::UploadedFile object containing complete information.

Please, how can I pass image to the uploader to be properly processed, mime type stored and created derivatives?

If I try this.

attacher = Shrine::Attacher.from_model(new_image, :image)
      attacher.assign(image)

inside image is path to image, it fails on:

*** JSON::ParserError Exception: 784: unexpected token at

And if I pass File.open(image) to assign method, I get uploaded orignal image, but without mime-type and without derivatives.

I am little bit confused.

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

I have a solution.

Shrine uploader needs a File object opened in binmode, so

        image: File.open(image, binmode: true)

In creating instance of model class.

0
On

Sometimes when you see this parse error, it's because the record already has some data in the column you are trying to update. So it tries to read this column as JSON, but since it may be a string or random characters then it will fail. Try to see if there is non null or non JSON {} value in your database.