我有一个带有postgres(9.6)的rails(5.1)应用程序作为数据库。在其中一个表中我有jsonb字段,我需要的只是检索此字符串并将其发送到客户端。我为什么需要它?转换为json需要一半的总请求时间
my_record.my_json_field # returns hash
my_record.read_attribute(:my_json_field) # also returns hash
# even this hack returns hash
MyRecord.select('my_json_field as temp_field').first[:temp_field]
我找到了两个解决方案:
# proposed by Sergio Tulentsev
# It's a fastest way. you will receive just a hash with fields that you selected
MyRecord.connection.execute(MyRecord.my_scope.to_sql)
# Another option is to select that data as a text.
# In that case you will receive ActiveRecord objects
MyRecord.select('*', 'my_json_field::text as my_field_as_text').first.my_field_as_text
答案 0 :(得分:2)
(从评论中移植建议)
尝试MyRecord.connection.execute_sql
(或称之为什么)。在上面的所有示例中,您将浏览模型,该模型尊重您的模式并反序列化哈希。您需要原始数据库连接。