2016-08-10 63 views
0

我是一名新的rails用户,我需要堆栈帮助!Rails将csv导入到模型中的数据库中

我搜索加载一些CSV数据库中的文件,我使用的是postgres。为此,我在我的模型

class Station < ApplicationRecord 
    def self.import_from_csv() 
    CSV.foreach('resources/locations.csv', headers: true) do|row|                 
     station = Station.new(
     id: row[0].to_i, 
     name: row['Name'], 
     city: row['City'], 
     default_dest: row['Default dest'], 
     public: row['Public'] == 'true', 
     lat: row['Lat'].to_f, 
     long: row['Long'].to_f 
    ).save! 
    end 
    end 
end  

在我控制器

def index 
    respond_to do |format| 
    format.html { 
     @stations = Station.all 
     render 
    } 
    format.json { 
     @total = Commute.count 
     @commutes = Commute.filter(params) 
     render 
    } 
    end 
end 

在我schema.rb了这个方法,这和这

create_table "stations", force: :cascade do |t| 
    t.string "name",   null: false 
    t.string "city",   null: false 
    t.float "lat",   null: false 
    t.float "long",   null: false 
    t.boolean "public",  null: false 
    t.string "default_dest" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

但是,没有数据在我的数据库中加载...

也许有人知道是否有耙子commande,我必须跑或类似的东西?

+0

您的服务器日志上的任何错误? –

+0

不幸的是.. – maluss

回答

0

您可以这样认真地继续,我会用Station.create!(...)替换Station.new(...).save!

您很快就会遇到问题。如果你正在导入许多记录,你的方法将持续很长时间。请使用activerecord-import宝石,并做到这一点:

class Station < ApplicationRecord 

    def self.import_from_csv 
    stations = CSV.foreach('resources/locations.csv', headers: true).map do |row|                 
     Station.new(
     id: row[0].to_i, 
     name: row['Name'], 
     city: row['City'], 
     default_dest: row['Default dest'], 
     public: row['Public'] == 'true', 
     lat: row['Lat'].to_f, 
     long: row['Long'].to_f 
    ) 
    end 
    Station.import(stations) 
    end 
end  
+0

谢谢我通过创建和使用这个宝石来改变新的,然后我重新启动我的服务器,但没有任何变化... – maluss

+0

为什么这会很长?这会在我每次使用应用程序或第一次执行时执行? – maluss

+0

@maluss他意味着如果你坚持你的初始方法,它会很长。该方法只会在你调用它时运行 – lusketeer

相关问题