How do I handle increasing the amount of images I accept on a model?

I have a Post model, and now users can only upload 1 image - which is handled by Carrierwave and pushed to S3 via Fog.

But I want to handle multiple, and I know this will require some refactoring of the model. i.e. I have to break out the images into their own model and add Carrierwave to that model and then just associate those records with my Post model.

But, how do I handle the current posts that have a single image stored on S3 via Carrierwave?

I haven’t quite wrapped my head around that yet.

Ideas?

I’d create two migrations: one to create the new Image model/table, and another that migrates existing image data to new Image models and associates them correctly.

Make sense?

2 Likes

Does your file path need to change?

If so, there’s not a whole lot you can do with the S3 console alone if you have lots of images. Amazon’s S3 console is extremely dumb. You’re probably best off copying the folder structure on your local file system somewhere, restructuring the folders as needed and using a tool like s3cmd to sync the entire folder structure recursively with your bucket. Then whenever you get your codebase updated to make use of the associations remove the old stuff on S3, or leave it if you have anything linking to it directly.

I’ve ran into a particularly troublesome issue before where I had S3 image references hard-coded into HTML-based text fields in my database. Eventually requirements changed I had to updated the file paths for all of the images. I couldn’t find a good way to update the paths stored in the database directly (they were far too numerous to update manually) so I ended up using rack-rewrite to redirect all the old paths to the new one. A bit of a shim, but it worked reliably.

1 Like

This certainly does. So the second migration is literally like a RakeTask that just includes regular old ruby?

It shouldn’t have to change, no. I am not really a big fan of manually hardcoding paths, I would much prefer if Carrierwave & Fog did this.

Thanks for the hat tip on rack-rewrite & s3cmd though. They both seem interesting, and I may have use for them in the future. Rack-rewrite actually solves a problem I had before, with trying to figure out how to apply Apache Mod_Rewrites to Rack Middleware. So thanks much for that.

Well, it’s kind of a rake task in that you run it with rake, but I’m suggesting you put the code in the up method in a migration file.

Also, it’s a good idea to use pure SQL for this instead of writing Ruby and using active_record. This is because you might one day delete the Image model from your app. Then, if you tried to run migrations, they would refer to Image, which would no longer be a constant.

Ahhh…interesting, re: the SQL.

That should be…muy interesante and makes a lot of sense.

You can likely find a few examples of this in the db/migrate folder in our Upcase repo.

1 Like