title: Rails 3 - Building forms from Serialized Data
body: <p>I've been working on a rails project where I am needed to serialize permissions for user roles and store in the database. As far as that goes I'm all good. Now my problem comes when I want to modify the serialized data from a rails generated form.</p>
  
  <p>I acted on instinct and tried with the expected behavior.
  That would be to use something like this:</p>
  
  <pre><code>f.check_box :permissions_customer_club_events_read
  </code></pre>
  
  <p>But as no getters or setters exist for the serialized data, this doesn't work (obviously :p). Now I wonder how I would go about tackling this problem and the only thing that comes to mind is <strong>dynamically generating</strong> getter and setter methods from my serialized hash.</p>
  
  <p>Example:</p>
  
  <pre><code>def permissions_customer_club_events_read=(val)
    permissions[:customer][:club][:events][:read] = val
  end
  
  def permissions_customer_club_events_read
    permissions[:customer][:club][:events][:read]
  end
  </code></pre>
  
  <p>Anyone understand what I'm getting at?</p>
  
  <p>Here is my <strong>Model</strong>:</p>
  
  <pre><code>class User::Affiliation::Role &lt; ActiveRecord::Base
    require 'yajl'
  
    class YajlCoder
      def dump data
        Yajl.dump data
      end
      def load data
        return unless data
        Yajl.load data
      end
    end
  
    serialize :permissions, YajlCoder.new
  
    after_initialize :init
  
    def init
      ## Sets base permission structure ##
      self.permissions ||= YAML.load_file("#{Rails.root}/config/permissions.yml")
    end
  
  end
  </code></pre>