0

I have a form that will have both a dynamic set and a known set of fields. I need a way of storing the dynamic fields in the database and I have decided on storing them in a serialized field, as I will not need to search on the data, and I just need it stored and recalled when needed.

class MyApplication < ActiveRecord::Base
    has_one :applicant
    belongs_to :member

    serialize :additional_fields, Hash

    accepts_nested_attributes_for :applicant, :additional_fields

I was thinking of having the form return the fields as an additional_fields_attributes and somehow have the model look after storying the hash into the additional_fields section. Im not sure if I have to go as far as using something like method missing to look after this, or if I should scrap the accepts_nested_attributes_for and handle it on my own.

Does anyone have any thoughts?

Thanks! Ryan

2 Answers 2

1

I just tested what you suggest.

You don't need: accepts_nested_attributes_for :additional_fields

Just add in your form html like:

<input name="my_application[additional_fields][first]" type="text" /> 
<input name="my_application[additional_fields][second]" type="text" /> 

it will save a Hash with keys: first and second

You could put in your model an array of fields, say in your User model:

FIELDS= ["item1", "item2"]

In your view:

<% User::FIELDS.each do |field|%>
     <input name="my_application[additional_fields][<%= field %>]" type="text" /> 
<% end %>
4
  • Is there a way to turn those hash keys into methods? For example use my_application.additional_fields.first
    – lundie
    Feb 6, 2011 at 4:03
  • this should answer: stackoverflow.com/questions/4910326/… Feb 6, 2011 at 9:56
  • That works if you know that the fields are going to be. In my case the form is dynamically generated, and each application may have different fields. Is there a way to deal with this using something like meta programming to generate the required methods from what is contained in the Serialized Hash?
    – lundie
    Feb 7, 2011 at 16:12
  • I'm not sure of what you expect but my answer is edited. If it doesn't fit, please give details. Feb 7, 2011 at 16:34
1

I ended up using this tutorial http://www.kalzumeus.com/2009/11/17/practical-metaprogramming-with-ruby-storing-preferences/ which worked really well.

Thanks for your help!

1
  • This was indeed a nice article. For reasons I don't yet understand after a few days of Ruby/Rails programming, I had to scope the serialized "options" variable with "self" in the two metaprogrammed attribute methods. Otherwise options appears to be scoped locally to those methods. I'm on Rails 3 and Ruby 1.8.7.
    – sowbug
    Mar 24, 2011 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.