How to edit a Rails serialized field in a form?

后端 未结 8 694
-上瘾入骨i
-上瘾入骨i 2020-12-04 07:16

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

class Widget < ActiveRecord::Base
  serialize :options
end

The opti

8条回答
  •  一生所求
    2020-12-04 08:05

    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
    
      def self.serialized_attr_accessor(*args)
        args.each do |method_name|
          eval "
            def #{method_name}
              (self.options || {})[:#{method_name}]
            end
            def #{method_name}=(value)
              self.options ||= {}
              self.options[:#{method_name}] = value
            end
            attr_accessible :#{method_name}
          "
        end
      end
    
      serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
    end
    

    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
    

提交回复
热议问题