我有一个rails(5.1)应用程序,postgres(9.6)是DB。在其中一个表中,我有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

最佳答案

(从评论中移植建议,有效)
尝试MyRecord.connection.execute_sql(或它的名称)。在上面的所有示例中,您都将遍历模型,该模型将尊重您的模式并反序列化散列。您需要原始数据库连接。

关于ruby-on-rails - 是否可以从数据库检索json?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47528133/

10-10 04:26