I’ve got three relationships:
Package, PackageItemGroup, and PackageItem
[Package] has_many :package_item_groups,
has_many :package_items, :through => :package_item_groups
[PackageItemGroup] has_many :package_items, belongs_to :package
Ok, I need a form that will build params like this upon submit
:package => {
:name => “Package Name”,
:package_item_groups => [
{:package_items => [{:item_id => “2”}, {:item_id => “3”}]},
{:package_items => [{:item_id => “4”}, {:item_id => “5”}]}
]
}
Using fields for on package_item_groups with a form name like
“package[package_item_groups][]” works fine. The params returned from
that look ok. It’s when you try and add the third level of
association with package_items fields_for, becuase
“package[package_item_groups][][package_items][]” does not work, as it
is a completely invalid array.
Here is what I did to get params that I could use, I created a
counter, that would serve as an index for the package_item_groups
array. This counter would create key values that didn’t mean
anything, aside from the form associating the correct package_items
and package_item_groups together.
This is an example:
<% fields_for “package[package_item_groups][]”,
PackageItemGroup.new, :index => Counter.index %>
Counter.index being a integer value that I can store in session, keep
track of, and increment / decrement when needed.
This solution WORKS, but it SUCKS. It’s very ugly, and essentially a
hack. Also, the above solution is only for the new form, the edit
form has to be different, which makes it a pain in the neck to
maintain.
Has anyone else tried this before? Any luck with a more elegant
solution that mine? I’ve googled, but had a very difficult time
finding people in the same boat, perhaps this is just too much to
expect from a simple web application, I dunno. Some comments would be
very welcome and helpful.