views:

31

answers:

0

I've got a model that has a serialized hash as a field. I'm trying to create a form that enables users to fill this out. Is there a way to use Rails form_for helper to concisely build the hash?

The model is an Article, and an Article can have many authors which are stored in a serialized hash.

class Article
  serialize :authors, Hash
end

The authors hash stores information about each author that contributed to the Article, and can have many optional attributes. The authors are keyed by the order in which they should appear. Here is an example of what such a hash may look like:
{1 => {:name => "William Jones", :contribution => "Wrote the body of this question"}, 2 => {:name => "Billy Bob", :contribution => "Got coffee for William", :level => "Minor"}

I've got a form that kinda works for this, where I use the form_for Rails helper, but I'm forced to use text_field_tag and other non-model specific helpers to generate the authors hash. For example, where key_num is a variable passed into a partial:

<%= text_field_tag "article[authors][#{key_num}][name]", 
    article[authors][#{key_num}] ? article[authors][#{key_num}][:name] : nil %>

Obviously, this is pretty darn ugly and unclear. Is there a better way to do this I'm missing?

I'm versioning the Articles, and for that among other reasons, it is hugely helpful to use a serialized Hash instead of spinning this authors concept into a separate sub-model.