Relevant info
- I have a User model with plenties of attributes and several has_many associations.
- I have a BIG form to edite existing user info, including nested fields.
- I have divided the form into several forms in different divs and show only one form at a time. (i.e. tabs in UI)
- User can save info by clicking Save button, which submits currently visible part of form via Ajax. No page reload. Just updating a status box with rjs.
- I use Ryan Bates example to dynamically add fields for nested models.
Problem
If a user adds fields for associated models using js
and submits form n times
n new associated models are created
this happens because js-added fields have no hidden_field for id attribute and every time form is submited, params do not include id for that specific nested record. i.e. first time it is ok, after second ajax post request (reminder - page does not reload) that record should be updated, but instead new record is being created because there were no id parameter passed for this already existing record.
Question
Should I make dirty hacks in controller to find out if new records should be saved and if they are - update dynamically added form in view by adding hidden field with newly saved record id value. The question is - how do I do it gently, writing the most maintainable and robust code possible?
At the moment update action is dead simple, with ideas of dirty hacks commented
def update
@user = current_user
respond_to do |wants|
wants.js {
#analyze parameters to find out which
#nested model is going to be saved (not updated)?
#also save identifier of nested record in view i.e. {...."324324234" => {:a => 1, :b => 2, .... etc}}
@user.update_attributes(params[:user])
# check if the record of the model was saved and take it's id;
# use identifier 324324234 to find nested form and insert hidden
# field with record id using rjs
}
end
end
I hope I have defined my problem clearly. I would really like to avoid such hacks and write pretty code. I also wouldn't like to reload the page or part of it with ajax. Any suggestions?