我找不到包含所有数据类型列表的活动记录文档页面。
有人可以帮我吗?
Answers:
如果你在谈论的类型迁移,如字符串,整数,日期时间等,然后你想要的ActiveRecord :: ConnectionAdapters :: TableDefinition,该列方法。(Rails的5编辑:又见连接add_column。)
在此更新中,标准类型为:
:primary_key
:string
:text
:integer
:bigint
:float
:decimal
:numeric
:datetime
:time
:date
:binary
:boolean
:decimal
每个数据库的实现都不同,因此,如果可能的话,我会避免使用它。您可以使用不在此列表中的类型,只要您的数据库支持该类型(例如,:polygon
在MySQL中),但这就不会与数据库无关,因此也应避免。
您还可以在源中看到ActiveRecord数据类型。每个DBMS适配器都包含其自己的映射。例如,在MySQL情况下,请查看以下文件:https : //github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb#L148或通过此代码行获取当前文件DBMS适配器:
ActiveRecord::Base.connection.native_database_types.keys
请注意,这基于日期为2015年2月13日的Rails源代码(Rails 4.2)
如果有人想看看如何将这些数据类型映射到您正在使用的数据库中。
您可以在github上轻松获取Rails源代码。
例如
Rails数据类型到mysql数据类型的映射。
NATIVE_DATABASE_TYPES = {
:primary_key => "int(11) auto_increment PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 },
:text => { :name => "text" },
:integer => { :name => "int", :limit => 4 },
:float => { :name => "float" },
:decimal => { :name => "decimal" },
:datetime => { :name => "datetime" },
:time => { :name => "time" },
:date => { :name => "date" },
:binary => { :name => "blob" },
:boolean => { :name => "tinyint", :limit => 1 }
}
在https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb#L148中找到
如果有人想在这里使用postgreSQL,那就去吧。
NATIVE_DATABASE_TYPES = {
primary_key: "serial primary key",
bigserial: "bigserial",
string: { name: "character varying" },
text: { name: "text" },
integer: { name: "integer" },
float: { name: "float" },
decimal: { name: "decimal" },
datetime: { name: "timestamp" },
time: { name: "time" },
date: { name: "date" },
daterange: { name: "daterange" },
numrange: { name: "numrange" },
tsrange: { name: "tsrange" },
tstzrange: { name: "tstzrange" },
int4range: { name: "int4range" },
int8range: { name: "int8range" },
binary: { name: "bytea" },
boolean: { name: "boolean" },
bigint: { name: "bigint" },
xml: { name: "xml" },
tsvector: { name: "tsvector" },
hstore: { name: "hstore" },
inet: { name: "inet" },
cidr: { name: "cidr" },
macaddr: { name: "macaddr" },
uuid: { name: "uuid" },
json: { name: "json" },
jsonb: { name: "jsonb" },
ltree: { name: "ltree" },
citext: { name: "citext" },
point: { name: "point" },
bit: { name: "bit" },
bit_varying: { name: "bit varying" },
money: { name: "money" },
}