简体   繁体   English

Rails访问表字段中存储为JSON数据的字段

[英]Rails accessing fields stored as JSON data inside a field of a table

I have table Employee with several columns. 我有几列员工表。 One of the column is a text field and some data is stored inside it in following format, 该列之一是文本字段,一些数据以以下格式存储在其中:

:last_working_day => nil,
:first_working_day => <some data>,
:reason_for_leave1 => nil

and so on. 等等。 Above layout is just an example and not actual layout. 上面的布局仅是示例,并非实际布局。

I need to access these values. 我需要访问这些值。 I can access the field which contains these data but how to extract these as a key value pair? 我可以访问包含这些数据的字段,但是如何将它们提取为键值对?

You can start with this 您可以从这里开始

f.split(',').inject({}) { |h, e| k, v = e.split('=>').map{ |s| s.strip}; v = nil if v == 'nil'; h[k[1..-1].to_sym] = v ; h }

where 'f' is the field you provided. 其中“ f”是您提供的字段。 And seriously, use HStore or at least store this as YAML or json. 认真地,使用HStore或至少将其存储为YAML或json。 Rails can handle columns with data serialized as YAML automatically. Rails可以自动处理带有序列化为YAML的数据的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM