6

I have a column that stores JSON data. I don't know how to show it when it is on Edit state.

 serialize :value, JSON

 = f.fields_for :value do |ff|
    .form-group
      = ff.label :short  
      = ff.text_field :short, class: 'form-control'
    .form-group
      = ff.label :long
      = ff.text_field :long, class: 'form-control'
iamspauljamez
  • 287
  • 1
  • 3
  • 14

1 Answers1

30

In place of

= f.fields_for :value do |ff|

please use the following code:

= f.fields_for :value, OpenStruct.new(@object.value) do |ff|

You will need to replace @object with your model object.

Barry
  • 746
  • 9
  • 20
Manoj Menon
  • 1,028
  • 8
  • 18
  • Welcome! To know more about OpenStruct in ruby please take a look at http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct :) – Manoj Menon Sep 30 '14 at 09:19
  • 4
    You can also use `f.object` to reference the model object in the `OpenStruct` instead of making another fixed reference to your model object (in this case, `@object`). – Barry Jun 30 '16 at 09:19
  • be careful with `OpenStruct`. afaik, using it at runtime [clears the vm's method cache](https://mensfeld.pl/2015/04/ruby-global-method-cache-invalidation-impact-on-a-single-and-multithreaded-applications/), resulting in performance penalties. – glasz Nov 07 '17 at 23:53