ActiveRecord 可以在迁移之外创建表吗? [英] Can ActiveRecord create tables outside of a migration?

查看:27
本文介绍了ActiveRecord 可以在迁移之外创建表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个非 Rails 网络应用程序,因此默认情况下没有迁移脚本.

I am working on a non Rails web app, so no migrations script by default.

Sequel ORM 让我可以在脚本中轻松创建表:

The Sequel ORM lets me create tables easily in a script:

#!/usr/bin/env ruby

require 'rubygems'
require 'sequel'

## Connect to the database
DB = Sequel.sqlite('./ex1.db')

unless DB.table_exists? :posts
  DB.create_table :posts do
    primary_key :id
    varchar :title
    text :body
  end
end

有没有办法在迁移之外使用 ActiveRecord 做到这一点?

Is there a way todo this with ActiveRecord outside of migrations?

推荐答案

我目前的理解是不,所有修改数据或模式都必须通过迁移来完成.我在 github 上有 一个完整的 rakefile可用于在 Rails 之外执行迁移.

My current understanding is no, all modifications data or schema have to be done through a migration. I have a complete rakefile on github which can be used to perform the migrations outside of Rails.

或者,如果它只是一个初始化脚本,则可以使用以下内容.

Alternatively if it is just an initialisation script the following could be used.

ActiveRecord::Base.establish_connection(
   :adapter   => 'sqlite3',
   :database  => './lesson1_AR.db'
)

ActiveRecord::Migration.class_eval do
  create_table :posts do |t|
        t.string  :title
        t.text :body
   end

   create_table :people do |t|
      t.string :first_name
      t.string :last_name
      t.string :short_name
   end

   create_table :tags do |t|
      t.string :tags
   end 
end

这篇关于ActiveRecord 可以在迁移之外创建表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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