On Sat, 19 Jul 2008, MarkMT wrote:
>
> Ok, so this didn't attract any suggestions, but here fwiw is how I
> solved the problem...
>
> I still don't know exactly why I was ending up in the index view, but
> it seems that the underlying problem was that when the form was being
> resubmitted after validation failure, Rails was interpreting my
> form_for as an "edit" form, rather than a "new" form - and
> consequently putting a hidden _method = put parameter in the form
> markup.
>
> Apparently the reason it was treating this as an "edit" form the
> second time around is that the validation failure was happening in the
> "create" action on the embedded "fields_for" fields, but this only
> happened after the primary fields for the "form_for" had already been
> save! 'd. I had the whole thing wrapped in a transaction, which was
> correctly preventing the primary fields from actually making it to the
> db, but the objects themselves were still being treated as if they had
> been saved - even though they hadn't - and so Rails apparently figured
> that the purpose of the subsequent form was to edit this "existing"
> data.
>
> The solution: in my "create" action, I just moved the save! of the
> primary "form_for" fields to occur _after_ those embedded in
> "fields_for" have been save! 'd. This means that if the primary fields
> only ever get created if the embedded fields have successfully
> validated, i.e. the transaction as a whole is good.
You might look into the build method, which lets you create an
association in memory without saving, and then, assuming the
validations are in place, it will do an all-or-nothing save. That may
be a good defense against the (in my view) excessive "magic" of
form_for(@object) :-)
David
--
Rails training from David A. Black and Ruby Power and Light:
Intro to Ruby on Rails July 21-24 Edison, NJ
Advancing With Rails August 18-21 Edison, NJ
See http://www.rubypal.com for details and updates!