简体   繁体   English

如何通过Ruby Gem访问Rails DB

[英]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. 我正在尝试制作一个简单的Ruby Gem,它可以通过命令行可执行文件访问Rails数据库(例如sqlite)并将其导出到CSV文件。 I am having trouble figuring out how to get to the Database in order to convert the rows and such to CSV. 我在弄清楚如何进入数据库以将行等转换为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. 现在,我的直觉告诉我要查看ActiveRecord,但是我发现的所有信息都在Rails中调用了它,而不是通过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. 另外,如果有人对我可能会遇到的其他数据库格式的问题有任何见解,并从中转换(例如PostgreS或Mongo),将不胜感激。 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? 我应该在可执行文件(bin / [cmd])中还是在rake任务(无论是什么)中调用ActiveRecord还是其他功能? 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." 现在,我在lib / gem.rb文件中调用它( puts ActiveRecord.base.connection放进去,看它是否工作),但是在命令行上通过可执行文件(bin / gem)运行它,并得到一个“未初始化的常量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. 首先,如果您需要转储表或整个数据库,则可以使用纯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. 其次,如果不是这种情况,并且您需要从活动记录中提取信息并以CSV格式导出,则建议您查看CSV标准库。

http://ruby-doc.org/stdlib-2.1.2/libdoc/csv/rdoc/CSV.html 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. 在查看csv库之后,您可以执行以下伪代码。

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

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

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