Uploading a file in rails through Paperclip
As we know these days almost all the applications have the requirement to upload files to the application then be it an image , a video or any other file. I am writing this blog to share with you all a simple way of uploading an image file to your application. For that we will use Paperclip gem.
The steps are as fallows:
Step 1 : Go to your gemfile and add the paper clip gem to it.
gem "paperclip", "~> 3.0"
Then run command bundle install in your console.
Step 2 : Now create a model in which you have to store your attachment giving the name of the column as 'attached_file' and its data type as 'attachment'. let the model be Users. Now your user.rb file should look like thiis.
class User < ActiveRecord::Base
has_attached_file :attached_file
end
And your migration file that is 20160511110347_create_user.rb should look like this
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.attachment :attached_file
t.timestamps
end
end
end
Step 3 : Creating the controller to get your file permitted and saved in the model. The create method will get the attached file in the params save it to the database through the model. Now your users_controller.rb file should look like this.
class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to action_path
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:attached_file)
end
end
Step 4 : Now finally creating the view of your application through which you will let the user to upload a file. Your new.html.erb fin the views/user folder should look like this.
<%= form_for :user , url: users_path do |f| %>
<div class="field">
<%= f.label :attached_file %><br>
<%= f.file_field :attached_file %>
</div>
<% end %>
And there you go. Now you have successfully uploaded a file to your database.
0 Comment(s)