0

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?

sumitshining
  • 159
  • 1
  • 9
  • if it is json string then you can use `JSON.parse('your_string')`. – Manoj Monga Feb 20 '13 at 07:49
  • Can you post the schema of the table (at least the relevant part)? That said, if you are storing data like this in your database you might be better off using a Hstore than a text field. http://schneems.com/post/19298469372/you-got-nosql-in-my-postgres-using-hstore-in-rails – Alex Ghiculescu Feb 20 '13 at 08:12
  • @AlexGhiculescu Ghiculescu: I am not allowed to change the schema. So can't use Hstore. It has to be the way it is defined. – sumitshining Feb 20 '13 at 08:37
  • @SybariteManoj: Using JSON.parse is giving an ActionView error, ActionView::Template::Error (757: unexpected token at ':last_working_day => nil') – sumitshining Feb 20 '13 at 08:49
  • 1
    Title is a little misleading, because the format you provided is not json – cthulhu Feb 20 '13 at 09:18

1 Answers1

0

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. And seriously, use HStore or at least store this as YAML or json. Rails can handle columns with data serialized as YAML automatically.

cthulhu
  • 3,749
  • 1
  • 21
  • 25