Check if a table exists in Rails

后端 未结 5 561
旧时难觅i
旧时难觅i 2021-01-29 19:35

I have a rake task that won\'t work unless a table exists. I\'m working with more than 20 engineers on a website so I want to make sure they have migrated the table before they

5条回答
  •  感动是毒
    2021-01-29 20:07

    In Rails 5 the API became explicit regarding tables/views, collectively data sources.

    # Tables and views
    ActiveRecord::Base.connection.data_sources
    ActiveRecord::Base.connection.data_source_exists? 'kittens'
    
    # Tables
    ActiveRecord::Base.connection.tables
    ActiveRecord::Base.connection.table_exists? 'kittens'
    
    # Views
    ActiveRecord::Base.connection.views
    ActiveRecord::Base.connection.view_exists? 'kittens'
    

    In Rails 2, 3 & 4 the API is about tables.

    # Listing of all tables and views
    ActiveRecord::Base.connection.tables
    
    # Checks for existence of kittens table/view (Kitten model)
    ActiveRecord::Base.connection.table_exists? 'kittens'
    

    Getting the status of migrations:

    # Tells you all migrations run
    ActiveRecord::Migrator.get_all_versions
    
    # Tells you the current schema version
    ActiveRecord::Migrator.current_version
    

    If you need more APIs for migrations or metadata see:

    • ActiveRecord::SchemaMigration
      this is the ActiveRecord::Base class for the schema_migrations table
    • ActiveRecord::Migrator
      where all the action happens when migrations are run

提交回复
热议问题