Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Reading content from file and saving it to database in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 581
    Comment on it

    Hi friends,
      Sometimes we want to read the content from a file and save into our database. So we can achieve this in rails we do following:

       1) First you need to add a column in your model where you want to save the content of the text file so to add that (lets take an example Suppose the name of the model is article and you want to add the content in file_content column) you need to add the migration like this

     rails g migration AddColumnToArticles file_content:string

     

    This will create a migration like

    class AddFileColumnToArticles < ActiveRecord::Migration
      def change
        add_column :articles, :file_content, :string
       end
    end

     

     2) Run the migration

    rake db:migrate

     

    3) add a field  in your view like this:

     <%= f.label :file_content %>
     <%= f.file_field :file_content %>

     

    4) After that inside your controller you need to update the content of the params like

     def create
       file_content = params[:article][:file_content].read
       ## Here .read method is used to read the file content of the text file
       @article = Article.new
       @article.file_content = file_content
       @article.save
     end

    5) Thus the content of the file is saved in your table.

    Hope you liked this.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: