Rails often teaches me that other people have thought about my problems before I have but this time, I did not find anything...
I have 3 models :
Filesystem (I'm using Mongoid but I think the problem is the same with ActiveRecord)
has_many volumes and filesystems ; Volume
I define volumes and filesystems in the same 'node' form (with JS updating each filesystem's "volume" selectbox when a volume is added/changed/removed). This form works fine.
The problem resides when trying to persist filesystems when saving node :
As new volumes doesn't have any ID yet, I'm using volumes name as values in the selectbox, but the foreign key is the ID (names are unique within a node but different nodes will have volumes with same name, so I can't use name as an ID).
update actions, I need to find a solution to save volumes first, and then replace
params[:node][:filesystems_attributes] containing volume names by their respective IDs. This is very dirty and I'm wondering if it could be done in a clean way.
Has anyone else had the same issue?
The only really "clean" solution would be to save volumes and filesystems in different steps but my app really needs to be "less clicks is better" as
Node contains many other nested models (and forms).
Nested Attributes seems to be what you are searching for. Add them to your Node model and you should be ready to go.
accepts_nested_attributes_for :volumes, :filesystems
If you are using form helper
<%= form.fields_for :nodes do |nodes_form| %>
is the way to define the sub attributes.
I've just nested Filesystem into Volume instead of Node and it works like a charm.
Bad designs make bad questions ;o)