As we know that in almost all web applications we need to amend such a functionality where you need to get the content from a file stored externally in your pc. lets say this content to be a simple text content.
In these cases what we can do is use the input output reader classes of ruby.
This way we can upload the file to the memory. Read its contents and then save the content to the database and discard the file.
lets take an example where we can create articles in a web application with its title and description.
Now lets say we have a text file in our system and we want all the text to be uploaded as article's description from that text file so we need to do this.
First of all lets see the view file for the same i.e views/articles/new.html.erb
<h1>Upload Article</h1>
<p>
<%= f.label :title %><br>
<%= f.text_field :title,class:'form-control' %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description, rows: '5', class:'form-control' %>
or
<label for="file">Upload text File</label> <%= file_field_tag "file" %><br>
</p>
<p>
<%= f.submit(class:'btn btn-primary') %>
</p>
<%= link_to('Back', profile_path) %>
now as we can see we have used a file_field_tag in the description label and kept its name as "file".
Now the whole file will be stored in the file variable which we will access through params in the controller like this
Below is the controller file of articles controllers/articles_controller.rb
class ArticlesController < ApplicationController
def create
if params[:file].present?
uploaded_file = params[:file]
file_content = uploaded_file.read
article_hash = article_params
article_hash[:description] = file_content
@article = current_user.articles.new(article_hash)
else
@article = current_user.articles.new(article_params)
end
if @article.save
redirect_to article_path(@article.id)
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :description)
end
end
what we have done here is if the params has got a file key in it then the file will be accessed through params.
The .read method will read the contents of the file and send it into the hash to be saved in the database.
So this is how we can read text from text files and save it in out database.
0 Comment(s)