2014-07-17 65 views
0

我正在構建一個Rails gem,我可能需要知道當前可用的列類型。所以對於Postgres來說,我正在尋找類似於:ActiveRecord::Base.available_column_types。到目前爲止,我從源頭上看沒有成功。以編程方式獲取所有數據庫列類型

回答

1

我找不到ActiveRecord方法來得到你想要的。但我可以告訴你兩種方法,你可以實現這一點:

隨着任何路徑你需要創建一個初始化和猴子補丁ActiveRecord。例如:/config/initializers/active_record_extensions.rb。然後,選擇:

OPTION 1:根據您的模型得到的數據類型

class ActiveRecord::Base 
    def self.available_column_types 
    types = [] 
    ActiveRecord::Base.subclasses.collect{ |type| type.name }.each do |model_name| 
     types += eval("#{model_name}.columns.map(&:type)") 
    end 
    types.uniq 
    end 
end 

然後你就可以在終端上做rails console寫:

irb(main):001:0> User.available_column_types 
=> [:integer, :string, :text, :datetime, :boolean, :date, :hstore] 
irb(main):002:0> ActiveRecord::Base.available_column_types 
=> [:integer, :string, :text, :datetime, :boolean, :date, :hstore] 
irb(main):003:0> 

OPTION 2 :根據您的需要獲取所有可能的數據類型db適配器

class ActiveRecord::Base 
    if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) and 
    ActiveRecord::Base.connection.instance_of?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) 
    types = ActiveRecord::Base.connection.execute("select * from pg_type;") 
    return types.inject([]) { |result, record| result << record["typname"] } 
    # Too much info on pg_type table, you can get whatever you need. 
    end 

    if defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) and 
    ActiveRecord::Base.connection.instance_of?(ActiveRecord::ConnectionAdapters::MysqlAdapter) 
    # I don't know, it's just an example. Yo can add all adapters you want 
    return 
    end 

    # maybe raise an Exception with NO ADAPTER! message 
end 

結束

再次,在您的控制檯上,您可以使用ActiveRecord::Base.available_column_types查看結果。

注意:您需要調整它以使其適用於您的寶石。

+0

優秀。我實際上最終做了一些選擇1(沒有eval)。謝謝! –

相關問題