Reputation: 19247
In my Rails 3.0 app, I'd like to add a form element where a user can create a series of up to 5 keyword/value pairs, to be stored in a single field. The keywords are defined by the user, not the app, so the other SO questions I've researched wont work because in those examples the code has to 'know' the keys ahead of time.
The key will always be a single word, the value will always be a single short sentence.
So 1 user might want to somehow enter the equivalent of: {'snow' => 'I like snow', 'ski' => 'I like to ski'}
Where another user might enter the equivalent of: {'red' => 'My favorite color is red', 'yellow' => 'Dont eat yellow snow'}
I get how to use the serialize :options, Hash for my model to the database stores/retreives the hash in a single a text field.
What I don't get is an easy way to allow the user to create/edit the hash without having to actually type it in json or hash format in a text_area field.
BRUTE FORCE: Since I have a fixed & small number of permitted pairs (5), in my view I could provide 10 fields for them to enter 0-5 pairs, then have the form save and show logic somehow move the pairs from/to those 10 fields. But I cannot figure out the logic to map those 10 fields to/from the serialized data. Any help would be appreciated.
ELEGANT: Even better of course would be a way to dynamically generate the hash-edit form elements. (I think I read Rails 3.2 has that capability but upgrading right now isn't possible as this is a large, complex app with a lot of moving parts (integration with multiple externals services) so we won't be updating to a newer rails for 4-6 months.)
Upvotes: 0
Views: 271
Reputation: 12818
Not a recipe, just few hints.
Brute force:
Create 10 virtual attributes for your model (key1, value1, key2, value2, ...
)
Use ActiveRecord callbacks to serialize / deserialize the hash
class YourModel < ActiveRecord::Base
attr_accessor :key1, :value1, :key2, :value2, ...
attr_accessible :key1, :value1, :key2, :value2, ...
after_initialize do |obj|
#map pairs to virtual attributes
unless obj.pairs.nil?
i=1
pairs.each_pair do |key, val|
obj.instance_variable_set("@key#{i}", key)
obj.instance_variable_set("@value#{i}", val)
i += 1
end
end
end
before_save do |obj|
#serialize top hash
end
end
Second way:
Create custom form builder that generates required fields ( here's example for radio buttons - Example of a rails custom formbuilder for a radiobutton list , you can easily find several screencasts and tutorials about form builders)
Upvotes: 1