Hi, I have a form that contains data for multiple records from a DB
table and that allows me to add new fields, corresponding to new DB
rows using a little ajax response to an “add item” link. Before I
added the ability to add new fields, my controller had something like
to do the update. Works fine.
However, I’m trying to figure out the best way to handle the case
where the form includes both existing and brand new records.
Initially, I had the new database records created as part in the
action that responds to the “add item” request. The Item.update in the
action that gets the form submit then works just as before.
The problem is that I now also have “validates_presence_of” on the
item’s fields in the model - which means I can’t create the new item
when I’m adding the form fields if I don’t already have the data to
put in it.
What’s the most elegant way to deal with this?..
I don’t want to leave the create in the ajax action for the “add item”
link and make the validation apply only to updates, because if someone
adds a field for a new item to the form but never completes the
submit, I don’t want to be left with a bogus record in the DB.
So when I submit the form, some of the data in the params hash need to
be used to update existing records and some needs to be used to create
new records. I guess I can iterate through the fields and test a find
statement for each, but this seems kind of messy.
Is there a smarter way to do this?