I've only just started learning ruby on rails and I would like to create an application that will allow me to add files to the database. Currently, I'm developing the rails application using the Aptana plugin for Eclipse and the application is using the default sqllite db.
I have tried generating a scaffold with the following parameters: documents title:string file:varbinary
. Then I do a 'rake'->'db'->'migrate'. When I migrate to localhost/documents and click on 'New Document' the application fails and displays an error.
What I would like to do is click on 'New Document', have a field that will allow me to browse for a document on my local computer, select the document and add it to the db on the rails applicatio开发者_运维技巧n.
Paperclip is more recommended than attachment_fu these days. It is really simple and easy to use with your active record model.
Is it a particular kind of file you want to add?
I just ask because if it's not data of a kind that benefits from being in a database ( textual data might be searchable, binary data is not ) then you are much better storing it in the filesystem and serving it up straight - especially for stuff like images or video - rather than inserting it into a database and having to go through your application every time a user requests it.
I'm not saying that there aren't any reasons you might want to have a file in the database, but I treat that as a last resort and in ten years of web programming I've not come across a case where it was necessary.
I would highly recommend the attachment_fu plugin as this lets you create models with attachments pretty nicely, Paperclip plugin is another good one also!
If you have trouble deciding which one to use, as far as i can remember, Paperclip makes it easier for multiple attachments, such as an Album has many Photos, and Attachment_fu is easier for single attachments such as a User has one display picture.
We do something like this on a site I'm managing. Instead of storing these files in a database, I'd agree with the other posters here and recommend you try something like Paperclip.
One caveat: if you want access control, make sure that paperclip doesn't save your files somewhere under /public, where anyone could possibly access them if they knew the URL. Deliver files to the user via send_file in your controller.
精彩评论