(Rails) 有没有办法检查字段的数据类型?

(Rails) 有没有办法检查字段的数据类型?

问题描述:

如何检查从数据库中检索到的数据类型是什么?

How do you check what the datatype is for something that was retrieved from the database?

例如,如果我有一个带有数据库字段title"的模型@model 的实例化,我希望能够编写类似@model.title.type 的代码并让它返回String".Rails 有任何内置功能吗?

For example, if I have some instantiation of a model @model with a database field "title", I want to be able to code something like @model.title.type and have it return "String". Does Rails have any built-in functionality for this?

试试这个:

@model.column_for_attribute('title').type

应该返回:string:text:integer

ActiveRecord Column 类还包括许多其他属性:默认、限制、名称、空值、精度、主要、比例、sql_type、类型.

The ActiveRecord Column class also includes a number of other attributes: default, limit, name, null, precision, primary, scale, sql_type, type.