代码之家  ›  专栏  ›  技术社区  ›  Justin Bozonier

如何判断数据映射器中是否存在表

  •  0
  • Justin Bozonier  · 技术社区  · 14 年前

    此代码在最后一行失败,特别是由于检查表\是否存在?如何在DataMapper中正确执行此操作?

    
    require 'sinatra'
    require 'DataMapper'
    
    DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/blog.db")
    
    class Post
        include DataMapper::Resource
        property :id, Serial
        property :title, String
        property :body, Text
        property :created_at, DateTime
    end
    
    DataMapper.finalize
    
    # automatically create the post table
    DataMapper.auto_migrate! unless Post.table_exists?
    
    2 回复  |  直到 14 年前
        1
  •  5
  •   snusnu    14 年前

    贾斯廷,

    如果你有 dm-migrations 必需的(这基本上意味着您无论如何都在使用RDBMS适配器),您可以执行以下操作来确定表(或该表中的列)是否存在。

    # Find out if the table named 'people' exists
    DataMapper.repository(:default).adapter.storage_exists?('people')
    
    # Find out if there's a 'name' column in the 'people' table
    DataMapper.repository(:default).adapter.field_exists?('people', 'name')
    

    请注意,这些API方法只能混合到 adapter 如果 DM迁移 是必需的,您正在使用 DataObjectsAdapter 后裔。

        2
  •  1
  •   Reactormonk    14 年前

    你可以使用 DataMapper.auto_update! 它应该是非破坏性的(只添加表/列)。

    推荐文章