如何通过在Ruby Rails平台中运行sql脚本为mysql数据库设置种子? [英] How to seed mysql database by running sql scripts in Ruby Rails platform?

查看:73
本文介绍了如何通过在Ruby Rails平台中运行sql脚本为mysql数据库设置种子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是Ruby Rails的Java程序员和初学者.在Java中,要运行数据库种子ant任务,该ant任务将执行SQL脚本. SQL脚本基本上是一组插入语句.

I have been basically java programmer and beginner for Ruby Rails. In java, to seed database ant task is run, the ant task execute SQL script. SQL script is basically set of insert statements.

我希望Ruby Rails平台上必须有一些等效的ant任务才能运行sql脚本?

I expect there must be some equivalent of ant task on Ruby Rails platform for running sql script?

针对Nikita的回答进行了

Edited in response to answer by Nikita:

尽管可以将迁移"用作种子数据的一种方式.但是我不想做重新编写与sql脚本相对应的迁移类的工作.所以我需要一些解决方案,通过该解决方案,我只需要执行sql脚本文件即可.我只想通过sql代码按数据库进行管理.

Although one can use Migration as one of way for seeding data. But I don't want to do rework of writing migration classes corresponding to sql scripts. so i need some solution through which i have to exec sql script file only. I want to manage by database only through sql code.

推荐答案

我个人不喜欢使用迁移来播种大量静态"数据.您可以通过以下方式轻松地从db/seeds.rb执行sql语句:

I personally don't like using migrations to seed large amounts of "static" data. You can easily execute sql statements from db/seeds.rb by:

# Empty the soon-to-be-seeded table
MyModel.delete_all

# Get the current DB connection
connection = ActiveRecord::Base.connection();

# Execute a sql statement
connection.execute("Insert INTO my_models (id, name) VALUES
    (1, 'Example 1'),
    (2, 'Example 2'),
    (3, 'Example 3');")

基本上,一旦有了当前连接,就可以使用connection.execute("SQL CODE HERE")调用sql语句.

Basically, once you have the current connection, you can just call a sql statement useing connection.execute("SQL CODE HERE").

这篇关于如何通过在Ruby Rails平台中运行sql脚本为mysql数据库设置种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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