Created
May 12, 2010 19:06
-
-
Save reu/399009 to your computer and use it in GitHub Desktop.
Custom attributes using serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% 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 %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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