插入Rails数据库 [英] Insert into Rails Database

查看:85
本文介绍了插入Rails数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ruby on Rails的新手,并且想创建一个爬网程序来抓取数据并将其插入数据库.我目前正在使用Heroku,因此无法直接访问数据库,并且想知道将爬虫脚本集成到RoR框架中的最佳方法是什么.我将使用每小时或每天的cron来运行脚本.

I'm new to Ruby on Rails and wanted to create a crawler that scrapes data and inserts it into the database. I'm currently using Heroku so I can't access the database directly and was wondering what the best way to integrate a crawler script into the RoR framework would be. I would be using an hourly or daily cron to run the script.

推荐答案

如果在Heroku上使用Rails,则只能使用Datamapper或ActiveRecord之类的ORM适配器.然后,这使您可以访问数据库,但基本上是通过一个层.如果您需要将原始sql发送到数据库,则可以,但是通常不建议这样做,因为ORM提供了您所需的几乎所有内容.

If you are using Rails on Heroku you can just use an ORM adapter like Datamapper or ActiveRecord. This then gives you access to your database but through a layer basically. If you need to send raw sql to the database you can but it's usually not recommended since the ORM's provide pretty much everything you need.

基本上,您将只在Rails应用程序中创建模型,如普通表和表中的关联字段.

You would basically just create models within your rails application like normal and the associated fields in a table.

rails g model page meta_title:string page_title:string

rake db:migrate # This has to be run on heroku too "heroku rake db:migrate" after you have pushed your code up

然后在您的搜寻器脚本中,只需使用模型即可创建记录...

Then in your crawler script you can create records by just using your model...

Page.create(:title => crawler[:title], :meta_title => crawler[:meta_title])

通常,您可以使用Whenever(https://github.com/javan/whenever)来管理您的cronjob,但是在Heroku上我不确定它的工作方式,因为我以前没有在Heroku上进行任何设置.

Normally you can use Whenever(https://github.com/javan/whenever) to manage your cronjobs but on Heroku I'm not sure how it works since I haven't set any up on Heroku before.

这篇关于插入Rails数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆