我正在使用带有 Rails 的 Postgres。有一个带有子选择的查询,它返回一个布尔值,但 Postgres 总是返回一个类似't'
or的字符串'f'
。但在生成的 JSON 中,我需要一个真正的布尔值。
这是我的查询:
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
or THEN 1
or THEN 'true'
,我都会得到一个字符串。所以我的 JSON 响应总是这样:
[
{"id":8, ..., "measurements_exist":"f"},
{"id":9, ..., "measurements_exist":"t"}
]
但它应该(!)看起来像这样:
[
{"id":8, ..., "measurements_exist":false},
{"id":9, ..., "measurements_exist":true}
]
有什么办法可以让这个工作正常吗?
谢谢!
解决方案:
只需给相应的模型(此处:)Map
一个属性访问器,用于value_as_boolean
转换值。因此,每次控制器尝试访问该值时,它都会自动使用属性访问器方法。
控制器代码:
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}
]