简体   繁体   English

将数据从sqlite导出到Rails中的csv文件

[英]Export data from sqlite to a csv file in rails

I have app that uses sqlite db and there are entries in that table. 我有使用sqlite db应用程序,并且该表中有条目。 Now i have to change sqlite to postgres . 现在我必须将sqlite更改为postgres And the table design is also changed. table design也改变了。

If it is the same table design then i would have gone to use taps or dump the data using yaml-db and then push the data to postgres, but in my scenario the table design also changes but i want to move the data from the sqlite to postgres according to the new table. 如果是相同的表设计,那么我会去使用taps或使用yaml-db转储数据,然后将数据推送到postgres,但是在我的情况下,表设计也会更改,但我想从sqlite中移动数据根据新表格发布邮件。

So i thought of exporting the data from sqlite to a csv file and then move the data from csv to postgres. 所以我想将数据从sqlite导出到csv文件,然后将数据从csv移到postgres。 Is this is the way i have to do or is there is any other way for doing it? 这是我必须做的方法还是有其他方法可以做? If this is the way then how can i export to csv and import to postgres ? 如果这样的话,我如何export to csvimport to postgres

Another thing is, after exporting the data from sqlite, is there is a way to push the data through migration ? 另一件事是,从sqlite导出数据后,是否有办法通过migration推送数据? please help me. 请帮我。

To export in a CSV format just add to a controller action a respond_to for csv and then in the matching view folder create a .csv.erb file to create the csv. 要以CSV格式导出,只需将对csv的response_to添加到控制器操作中,然后在匹配的视图文件夹中创建.csv.erb文件以创建csv。 This can then be called by just adding .csv to the URL. 然后,只需将.csv添加到URL即可调用它。

So your controller would be something like this: 因此,您的控制器将如下所示:

def index
  @people = Person.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @people }
    format.csv
  end
end

And you view which would be saved in a file (something like /app/views/people/index.csv.erb) would contain: 然后,您将查看将保存在文件中的文件(例如/app/views/people/index.csv.erb),其中包含:

First Name,Last Name
<% @people.each do |p| %>
  <%= raw "\"#{p.first_name}\"" %>,<%= raw "\"#{p.last_name}\"" %>
<% end %>

This way creating you CSV is not dependent on the database in use. 通过这种方式创建CSV并不依赖于所使用的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM