How to write rails database content to external file

I am trying to get rails to send the contents of my database to an external text file. I wanted this to be done every time a new user was created.

However, when I try to do the following in the user.rb model file,

before_save :write_data

def write_data()
    File.open("data.txt", "w") do |myfile|
        myfile.write(User.all)
    end
end

      

It doesn't write the actual content of the database, instead it displays something like this

User:0x109858540

      

Can anyone please help? Thank you.

+3


source to share


1 answer


User.all returns a Ruby object, and the method is probably write

saying "Hi, I'm expecting a string, this is not one, so I'll call the method to_s

."

So, you need to figure out how to turn your user list into some form that you can write to your text file, which is known as serialization. Ah, but in what format? XML? JSON? YAML? ... or the scary CSV format? There are built-in classes for converting ActiveRecord objects to various formats and gems for handling others. So I will assume that you call the method to_something

.

It also User.all

means that you want to write the entire user table (each record) to the corresponding file. (I think you might be asking yourself why, but that's a different topic). Thus, you will probably have to iterate over all user records.



The code is most likely more like

def write_data   # It ruby -- don't need no stinkin' empty parenthesis!! :-)
  my_file = File.open("data.txt", "w")
  User.all.each do |u|
    my_file.write u.to_something
  end
end

      

You may need to put a new line at the end of each line.

+3


source







All Articles