Hi,
this is slightly related to the "lazy_update" on associations thread -
I''m encountering a few problems and hope to get a few hints here as I
seem to be to narrow minded to find a good solution for this.
It''s not the first time I am facing this pattern but I''ll try
to explain
it using an example:
I have two models: Entry and Section. An entry habtm sections.
Now I want the user to be able to create a new entry or edit an existing
one and add sections to it or modify existing sections. But I want all
changes to the entry and its sections to be saved back to the database
only after the user explicitly tells me to by pressing "save".
So newly added sections (rendered using partials) should not be added to
the database immediately because they are ''invalid''. The user
presses
"add section" and the ajax helpers do what they do best and add
another
(e.g.) textaera to my form.
I have two problems:
- A new Section is added to the entry and initialized to empty but in
this state nothing should be written to the database. Empty sections are
to be discarded when finally saving to the database - I can do this with
AR Validations.
- Because the section is unsaved it not yet has an "id" but in my
template I iterate over all sections and add an textarea with a name
like "section[id]" (because the form helpers don''t support
this kind of
things with associations and in partials - or at least I don''t know how
to do it). This obviously works for existing sections but for the new
ones it won''t ("section[]") so I don''t know how to
deal with this kind
of problem.
What I did:
- I modified the Entry model to "proxy" these add (and delete)
requests
and only save them when they are supposed to. This kind of solves my
first problem (but it is ugly).
- I used a Counter class to assign "fake ids" to the new sections but
this leads to more problems and more ugliness in code and templates.
Well that is my little problem :)
I hope I managed to describe it in a halfway understandable way and I
further hope that I''m just to stupid to find the obvious
pattern/solution for this in Rails.
Thank you for your patience,
Lars
PS: I know that my english grammar leaves a lot to desire, sorry.