简体   繁体   中英

How to Access Rails DB via a Ruby Gem

I am trying to make a simple Ruby Gem that accesses a Rails Database (let's say sqlite) and exports it to a CSV file, via a command line executable. I am having trouble figuring out how to get to the Database in order to convert the rows and such to CSV. Right now my gut is telling me to look into ActiveRecord, but all the information I'm finding on that is calling it within Rails, and not through a gem. Also, if anyone has any insight into problems I might have with other DB formats and converting from those (like PostgreS or Mongo) it'd be much appreciated. Just trying to wrap my head around this matter.

Edit: I guess the real problem is that I don't know where to start with this. Should I be calling ActiveRecord in an executable (bin/[cmd]) or in a rake task (whatever that is) or what else? Right now I'm calling it ( puts ActiveRecord.base.connection to see if it works) in my lib/gem.rb file, but calling it to run via an executable (bin/gem) on the command line and getting a "uninitialized constant Gem::ActiveRecord."

There are a number of solutions for this on the interwebs. Firstly, if you need to dump a table or an entire database you can do that in pure SQL. Secondly, if that's not the case and you need to pull information from active record and export it in a CSV format, I would recommend looking into the CSV standard library.

http://ruby-doc.org/stdlib-2.1.2/libdoc/csv/rdoc/CSV.html

You could then pull rows from active record and format them accordingly. After looking into the csv library, you could do something not unlike the below pseudocode.

MyModel.where.....find_each do |row|
  csv << [row.name, row.number, row.otherthing]
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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