Today I was thinking about how to manage file uploads (mainly images) and not having to maintain them in the database. I wanted to take the approach of storing a reference to the image in the database (/public/photos/my_image.jpg) and have the image live on the file system.
Initially my Photo model extended ActiveRecord and I had to create an empty table called photos with just an ID field. Then I started thinking how ridiculous it was to have an empty table just to get the ActiveRecord class to behave. Since I didn’t want to place my image uploading code in the controller I embarked on a quest to figure out how to utilize a tableless model.
I didn’t have to journey far and decided to do something simple: create my model without extending ActiveRecord. Something like this:
class Image
def upload
File.open(”#{image_path}.jpg”, “wb”) do |file|
file.puts photo.read
end
end
end
The thought of something so simple actually working completely suprised me. I know the power of models when it comes to database abstraction, but was glad to find out that they can be decoupled from the database.