This is actually easy. You need to use a class with reader methods. You can create it in different ways, but the simplest is to use the OpenStruct class (note that it will not be able to see the fields that are in the methods of the OpenStruct instance ... this class cannot override methods).
In your form you must add:
<%= f.fields_for :wp_options, @profile.wp_options do |wp_options| %>
Instead of @profile (if you have a dynamic variable), you can use f.object.wp_options .
And for the Profile model, you should add the wp_options method.
def wp_options OpenStruct.new(self.attributes['wp_options']) end
In this case, it will only work if your serialized wp_options is a Hash class.
Hope this helps.
PS. I used the same technique, but since I had type hash keys, OpenStruct was unable to create it, so I used the simple Struct class. I had a data column:
def data keys = current_data.keys data = attributes[:data] Struct.new(*keys).new(*keys.map { |k| data[k] }) end
A little less trivial, but in any case the same approach (before that I created a special class, but now I know that Struct is the best way to create these kinds of things. You can find more ideas here: How to use hash keys as methods in the class ? )
Dmitry Polushkin
source share