When I started working with rails. Rails was on version 2 uploading a file was always kind of a dificult task. There was paperclip which was pretty neat to work with. It facilitates a lot the way to upload a file into a rails app. Shortly after I met carrierwave which I prefered because of the support it had to store multiple images and pre processed files with an Uploader declaration.
New times has come, and wiht it I discovery a new guy that does the same job and has a really nice support for rails 4.2. Meet refile. Just like paperclip and carrierwave it provides full support to manipulate images, validates types and facilitates data trasnfer with support to cloud servers like amazon s3.
To get started with refile first let's create a scaffold for post and later we will attach an image to the post.
bundle exec rails g scaffold post tittle:string content:text image_id:string
We added an image attribute with the sufix
_id, refile requires that to work. Do not forget that. Then is time to open our model and puts an attachement into it
class Post < ActiveRecord::BASE attachment :image end
Now we can integrate our upload input into our view with the refile helper to create a upload field at our
<%= form_for @post do |f| %> <%= f.attachment_field :image %> <% end %>
At our PostsController don't forget the change the permit of strong parameters to validates
image and not
def post_params params.require(:post).permit(:image) # not :image_id end
Now we are set. We can now create a new post with image and file upload. But now we need to vizualize then. Refile provides a helper for that. just add it to our view.
<%= image_tag attachment_url(@post, :image, :fill, 150, 150, format: "jpg") %>
Yey! now we have our app up and running with the refile gem.