views:

710

answers:

2

Note: Posting this as a separate question as per Brian's comment (from http://stackoverflow.com/questions/892624/how-to-handle-multiple-models-in-a-rails-form)

I'm trying to learn the best way to handle multiple models in a single rails form, when the models are both nested and non-nested. For the nested ones, I found these two tutorials to be helpful

http://weblog.rubyonrails.org/2009/1/26/nested-model-forms http://railsforum.com/viewtopic.php?id=717

My questions are:

  1. In the case of a non-nested model, how to handle multiple entries for the second model? Just run a loop, and use fields_for?
  2. In both nested/non-nested cases, how to validate for duplicate values, when there are multiple entries for the second model? For example, if project is the primary and task is the secondary (child) model, and the user adds multiple tasks for the project, how to make sure there aren't duplicate tasks added, for that particular model? One way would be to loop through the text values, and check for duplicates. Is there a better way to do it, at the object level, instead of string level?
+2  A: 

You might want to take a look at this to handle multiple instances:

http://railscasts.com/episodes/73-complex-forms-part-1

Also, I think I've answered your second question here:

http://stackoverflow.com/questions/889608/validating-multiple-models-in-a-rails-form/894645#894645

Jaryl
A: 

You should have a look at the Presenter Pattern, it helped me a lot!

You can start here:

http://blog.jayfields.com/2007/03/rails-presenter-pattern.html

ole_berlin