Tuesday, 20 August 2013

Dynamic Active Record Store accessors based off a user form?

Dynamic Active Record Store accessors based off a user form?

Active Record Store allows you to serialize parameters inside a single cell.
I.e.
class User < ActiveRecord::Base
store :options, accessors: [ :option1, :option2, :another_random_option ]
end
All the accessors are serialized inside the "options" column of the users
table now.
u = User.new
u.option2 = 'some option'
u.option2 # => 'some option'
This works great for my application because I have to create many forms on
a daily basis, where 90% of the form is the same (username, hobbies,
interests, etc.) and then 10% are schema-less (random_option_here,
another_random_option_in_another_form). I also never need to sort by the
schema-less options.
What I did was I created 1 table for the 90% of the form fields that are
always the same, and then I have another table with the last 10% of the
fields (the reason I have another table is because this is a belongs_to
relationship, so the user can have many rows in this table).
<%= form_tag do %>
<%= #render partial form for an object that has non-changing fields %>
...
<%= #render a schema-less partial form based off an ID passed here %>
<% end >
Now the only problem is that every time I create a new field in the custom
form, I have to add that parameter to the Active Record Store accessors,
otherwise I get a method missing error. It would be nice if I could just
go in and create as many View forms as I want for the schema-less fields
and never update the accessors in the Model.
So my question is: Is there anyway to dynamically add all the user
submitted custom fields to the accessors array, that way if the user
submitted fields "some_random_option1221", "another_option_here" then I
don't have to go into the accessors array and add that field?
Thanks!

No comments:

Post a Comment