views:

1959

answers:

1

I have a data model in my Rails project that has a serialized field:

class Widget < ActiveRecord::Base
  serialize :options
end

The options field can have variable data info. For example, here is the options field for one record from the fixtures file:

  options:
    query_id: 2 
    axis_y: 'percent'
    axis_x: 'text'
    units: '%'
    css_class: 'occupancy'
    dom_hook: '#average-occupancy-by-day'
    table_scale: 1

My question is what is the proper way to let a user edit this info in a standard form view?

If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.

What is the best/proper way to edit a serialized hash field like this in Rails?

+4  A: 

If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:

class Widget < ActiveRecord::Base
  serialize :options

  serialized_attr_accessor :query_id, :axis_y, :axis_x, :units

  def self.serialized_attr_accessor(*args)
    args.each do |method_name|
      method_declarations = <<<STRING
        def #{method_name}
          options[:#{method_name}]
        end
        def #{method_name}=(value)
          self.options[:#{method_name}] = value
        end
STRING
      eval method_declarations
    end
  end
end

I haven't played with serialize a bunch, so you might have to do some YAML conversion by hand as well in the evaluated method definitions. The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:

#haml
- form_for @widget do |f|
  = f.text_field :axis_y
  = f.text_field :axis_x
  = f.text_field :unit
austinfromboston
Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.
cpjolicoeur