以编程方式获取所有数据库列类型

时间:2014-07-17 18:05:31

标签: ruby-on-rails activerecord

我正在构建一个Rails gem,我可能需要知道当前可用的列类型。所以对Postgres说,我正在寻找类似的东西:ActiveRecord::Base.available_column_types。到目前为止,我查看了源代码并没有成功。

1 个答案:

答案 0 :(得分:1)

我无法找到ActiveRecord方法来获得您想要的内容。但我可以告诉你两种方法:

使用任何路径创建初始化程序和Monkey Patch ActiveRecord。例如:/config/initializers/active_record_extensions.rb。然后,选项:

选项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> 

选项2 :根据您的db adapter

获取所有可靠的数据类型
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查看结果。

注意:您需要对其进行调整,以使其适用于您的宝石。