Skip to content

Instantly share code, notes, and snippets.

@reu
Created May 12, 2010 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/399009 to your computer and use it in GitHub Desktop.
Save reu/399009 to your computer and use it in GitHub Desktop.
Custom attributes using serialization
<% form_for(@user) do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :custom, @user.custom do |custom_form| %>
<% custom_form.object.marshal_dump.each_key do |custom_field| %>
<p>
<%= custom_form.label custom_field %><br />
<%= custom_form.text_field custom_field %>
</p>
<% end %>
<% end %>
<p>
<%= f.submit 'Update' %>
</p>
<% end %>
require "ostruct"
class User < ActiveRecord::Base
serialize :custom
def after_initialize
self.custom = OpenStruct.new(custom)
end
before_validation :convert_custom_attributes_to_hash
after_validation :convert_custom_attributes_to_ostruct
def convert_custom_attributes_to_hash
self.custom = custom.marshal_dump if custom.kind_of? OpenStruct
end
def convert_custom_attributes_to_ostruct
self.custom = OpenStruct.new(custom) if custom.kind_of? Hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment