how to import data into rails?

后端 未结 2 685
栀梦
栀梦 2021-02-03 12:25

I have a Rails 3 application with a User class, and a tab-delimited file of users that I want to import.

How do I get access to the Active Record model outside the rails

相关标签:
2条回答
  • 2021-02-03 13:04

    Use the activerecord-import gem for bulk importing.

    Install via your Gemfile:

    gem 'activerecord-import'  
    

    Collect your users and import:

    desc "Import users." 
    task :import_users => :environment do
      users = File.open("users.txt", "r").map do |line|
        name, age, profession = line.strip.split("\t")
        User.new(:name => name, :age => age, :profession => profession)
      end
      User.import users
    end
    
    0 讨论(0)
  • 2021-02-03 13:25

    You can write a rake method to so. Add this to a my_rakes.rake file in your_app/lib/tasks folder:

      desc "Import users." 
      task :import_users => :environment do
        File.open("users.txt", "r").each do |line|
          name, age, profession = line.strip.split("\t")
          u = User.new(:name => name, :age => age, :profession => profession)
          u.save
        end
      end
    

    An then call $ rake import_users from the root folder of your app in Terminal.

    0 讨论(0)
提交回复
热议问题