如果我执行MyClass.columns,则列将具有type属性,其值如:integer,:string,:datetime等。如何获取该类型并将其映射到ruby类型?
例如:
:integer =>整数
:string =>字符串
:datetime => DateTime
我认为Rails可以使用规范的查找列表,但似乎找不到。理想情况下,我会找到一种适用于Rails支持的每个数据库适配器的方法。
答案 0 :(得分:-1)
您可以找到PostgreSQL in the source code on the official repo的“类型匹配”。
NATIVE_DATABASE_TYPES = {
primary_key: "bigserial primary key",
string: { name: "character varying" },
text: { name: "text" },
integer: { name: "integer", limit: 4 },
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" },
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" },
line: { name: "line" },
lseg: { name: "lseg" },
box: { name: "box" },
path: { name: "path" },
polygon: { name: "polygon" },
circle: { name: "circle" },
bit: { name: "bit" },
bit_varying: { name: "bit varying" },
money: { name: "money" },
interval: { name: "interval" },
oid: { name: "oid" },
}
我还要补充一点,那就是了解事情的幕后运作确实是一件好事,ORM的目标之一就是让您不必在意。您应该在迁移中使用ruby数据类型。
如果您要使用跨数据库解决方案,只需避免在每个DBMS上使用与之不匹配的类型(例如:decimal
)