Creating a ruby ​​file from CSV data?


I am trying to take the content of a CSV file, then use these contents to generate another file.

The approach I've taken is to import my data into a model (

Now I want to take the data from the database and create a text file.

I've created a Ruby file using:

target  = "target.rb"
content = "test", "w+") do |f|

I can't work out how to fill 'content' with the data from my data model.

Any suggestions?

My reputation is not high enough to ask you more questions about your requirements via comments, but here are a few facts that might help.

I am assuming that you have populated a Rails model with the information you need. I have no sample code from you so I'll provide an example with a 'Book' model. The Book model has a title and an author, both of type String.

target = "file.txt"
contents = ""

# Get all books as an array. Arrays have iterators so we can use 'each'
Book.all.each do |book|
  # get the book title, append it to the string. Add a newline

  # get the book author

  # Just a line separator
end, "w").write(contents)

The above would yield something like this inside the text file:

Book 1
Author 1
Book 2
Author 1

Reading up more on the Rails active records might help you as well: ActiveRecord