3

Activerecord を使用して mysql データベースに接続し、接続後にテーブルを作成します。問題は、テーブルが既に存在するかどうかを確認する方法がわからないことです。table.exist で動作すると思いましたか? しかし、どういうわけか私はしませんでした... ...だから、これは私がこれまでに得たものです:

ActiveRecord::Base.establish_connection(
        :adapter => "mysql",
        :host => "localhost",
        :username => "my-username",
        :password => "my-password",
        :database => "my-db",
        :encoding => "UTF8"
    )

    # How to check if it exists already? table_name.table.exist? doesnt really work...
    name = "my_table"
if name.!table.exist?
    ActiveRecord::Schema.define do
        create_table :"#{name}" do |table|
            table.column :foo, :string
            table.column :bar, :string
        end
    end
else
puts "Table exist already..."
end
    # Create ActiveRecord object for the mysql table
    class Table < ActiveRecord::Base
        set_table_name "#{name}"
    end
4

1 に答える 1

1

データベース接続で #tables メソッドを使用する必要があります。

unless ActiveRecord::Base.connection.tables.include? name
  ActiveRecord::Schema.define do
    create_table :"#{name}" do |table|
      table.column :foo, :string
      table.column :bar, :string
    end
  end
end
于 2012-05-04T20:58:31.880 に答える