我有一个RoR + MySQL的设置。在数据库中有一个Tinyint字段t。当我从Rails读取t的值时,我会得到true或false,因为Tinyint字段被Rails解释为布尔值。到目前为止都很好。
那么我如何从Rails中将该字段t读取为实际的整数呢?
我有一个RoR + MySQL的设置。在数据库中有一个Tinyint字段t。当我从Rails读取t的值时,我会得到true或false,因为Tinyint字段被Rails解释为布尔值。到目前为止都很好。
那么我如何从Rails中将该字段t读取为实际的整数呢?
http://apidock.com/rails/ActiveRecord/AttributeMethods/BeforeTypeCast/attributes_before_type_cast
例如:
Model.first.attributes_before_type_cast['your_boolean_field']
返回的值取决于您的数据库,对于PostgreSQL而言,其返回值可能是 'f' 或 't'
read_attribute_before_type_cast('your_boolean_field')
或者 your_boolean_field_before_type_cast
。 - Ben Visnessclass GroceryStore < ActiveRecord::Base
# rating is a TINYINT column
# we just redefine the method here to return the value cast how we want it
def rating
self.attributes_before_type_cast['rating'].to_i
end
end
grocerystore.rating
,你将得到一个整数而不是布尔值。
SELECT CONVERT(tinyintcolumn, [UN]SIGNED) FROM my_table
? - eggyal