Can ActiveRecord create tables outside of a migration?

六月ゝ 毕业季﹏ 提交于 2019-11-29 00:46:58

问题


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

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

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


回答1:


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



回答2:


In Rails 4 at least (possibly earlier?), you can call create table directly on an ActiveRecord::ConnectionAdapters instance, using the same syntax as the migration.

You can get a connection for your database (assuming you have only one database) by calling ActiveRecord::Base.connection. So, the Ruby for your example would look like:

unless ActiveRecord::Base.connection.table_exists?(:posts)
  ActiveRecord::Base.connection.create_table :posts do |t|
    # :id is created automatically
    t.string :title
    t.text :body
  end
end

Note: If you already have a model defined, and it uses the same database as the one in which you want to create the table, you can grab a connection object from there instead. For one-off table creation in the console, I'll call User.connection.create_table simply because it's less typing.



来源:https://stackoverflow.com/questions/2358903/can-activerecord-create-tables-outside-of-a-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!