How to add an image field into a Rails app?
I'm building a rails app that has an image upload field. I don't have any idea how to handle images in Rails. (The uploaded image would also require some processing as well.) Can anyone tell me how I can开发者_JAVA技巧 go about doing this?
thanks.
I would suggest using paperclip
.
This may help. And this.
Since May 14, 2018, paperclip is deprecated. Rails 5.2 now comes with active storage to solve image problems.
Are you uploading the image as a file to your rails app's directory, or into a database? Without knowing that or how your images are related to whatever data they are going with it's difficult to answer.
It can get a bit tricky if you're storing the files themselves in the database, but if you're only storing the path to the image it should be as simple as using an image tag with the stored path as the src; in the rails app that I did where images featured somewhat prominently, we had something that was a little messy, but looked like this:
<%= link_to "<span>fig." + (order+1).to_s + "</span>" + image_tag(url_for(:controller => 'upload', :action => 'picture', :id => picture.id), :class => 'list-image'), {:controller => 'upload', :action => 'show', :id => picture.id}, :class=>'head-image' %>
inside a pictures.each
block, where 'upload' was the controller which handled uploading and storing of images (we kept them in the database). The end result of that showed a picture scaled down (via css, we're naughty) that, when clicked, would take the user to the full-sized version of the picture (eventually we were going to do a pretty AJAX zoom/overlay, but never got that far).
Hopefully this is somewhat helpful, it's been several months since I've played with RoR.
EDIT: Ach, reading comprehension fail. I thought you were handling the uploading fine but were having trouble accessing the uploaded photos. I'm unfamiliar with Paperclip; we used Attachment_fu, with a tutorial here that made things pretty easy for us. (We actually used the instructions/tutorial in this book, I believe, but they seem similar.)
RMagick gem is very popular. I have used it for upload fields and also resizing images/converting to grey scale. It can be found here. Some common tasks are listed here.
You can also be interested in PaperclipPolymorph, it'a an extension of the Paperclip plugin that you could use to attach files to several models from what I understood.
精彩评论