Creating a form with unknown fields and storing those fields into a serialized filed in my model

寵の児 提交于 2020-01-06 12:42:26

问题


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


回答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 %>



回答2:


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!



来源:https://stackoverflow.com/questions/4899440/creating-a-form-with-unknown-fields-and-storing-those-fields-into-a-serialized-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!