需要将布尔值从Postgres(== String)转换为Ruby布尔值 [英] Need to convert a Boolean from Postgres (== String) to a Ruby Boolean
问题描述
我正在将Postgres与Rails结合使用。有一个带有子选择的查询,该查询返回一个布尔值,但是Postgres总是返回一个字符串,例如't'
或'f'
。但是在生成的JSON中,我需要一个真正的布尔值。
I'm using Postgres with Rails. There's a query with a subselect which returns a boolean, but Postgres always returns a String like 't'
or 'f'
. But in the generated JSON I need a real boolean.
这是我的查询:
SELECT
*,
EXISTS (
SELECT TRUE
FROM measurement
JOIN experiment ON measurement.experiment_id = experiment.id
JOIN location ON experiment.location_id = location.id
WHERE location.map_id = map.id
LIMIT 1
) AS measurements_exist
FROM "map"
我是否使用 THEN true
或都没关系然后1
或 true
时,我总是得到一个字符串。因此,我的JSON响应将始终如下所示:
It doesn't matter whether I use THEN true
or THEN 1
or THEN 'true'
, I will always get a string. So my JSON response will always look like that:
[
{"id":8, ..., "measurements_exist":"f"},
{"id":9, ..., "measurements_exist":"t"}
]
但是它应该像这样:
[
{"id":8, ..., "measurements_exist":false},
{"id":9, ..., "measurements_exist":true}
]
有什么方法可以使此工作正常吗?
Is there any way to get this working right?
谢谢!
只需为相应的模型(此处为 Map
)提供一个属性访问器,该访问器便使用 value_as_boolean
来转换值。因此,每次控制器尝试访问该值时,它都会自动使用属性访问器方法。
Just give the corresponding model (here: Map
) an attribute accessor, which uses value_as_boolean
to convert the value. So every time the controller tries to access the value, it uses the attribute accessor method automatically.
控制器代码:
class MapsController < ApplicationController
def index
select = ["*"]
select.push(measurements_exist) # This will just insert the string returned by the 'measurements_exist' method
maps = Map.select(select) # Results in 'SELECT *, EXISTS (...) AS measurements_exist FROM "map"'
render json: maps
end
private
def measurements_exist
"EXISTS (
SELECT TRUE
FROM measurement
JOIN experiment ON measurement.experiment_id = experiment.id
JOIN location ON experiment.location_id = location.id
WHERE location.map_id = map.id
LIMIT 1
) AS measurements_exist"
end
end
模型代码:
class Map < ActiveRecord::Base
def measurements_exist
ActiveRecord::ConnectionAdapters::Column.value_to_boolean(self[:measurements_exist])
end
end
结果JSON:
[
{"id":7, ..., "measurements_exist":false},
{"id":6, ..., "measurements_exist":true}
]
推荐答案
ActiveRecord的方法称为 ActiveRecord :: ConnectionAdapters :: Column.value_to_boolean
,它在内部将所有类似true的值转换为Ruby true
值。
ActiveRecord has a method called ActiveRecord::ConnectionAdapters::Column.value_to_boolean
it uses internally to convert any true-like value to a Ruby true
value.
您可以在代码中使用它。
You can use it in your code.
这篇关于需要将布尔值从Postgres(== String)转换为Ruby布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!