views:

903

answers:

1

http://weblog.rubyonrails.org/2009/1/26/nested-model-forms

This post helped in learning how to handle multiple models in a rails form. It works as long as the models are nested. what if they are not? lets say, I have a form, where the user fills personal details, address details and a bunch of checkboxes specifying her interests. There are at least 3 tables involved in this one single form, what is the best way to handle this, without having 3 different save buttons?

+2  A: 

Two options:

First is ActivePresenter which is perfect for this.

http://github.com/giraffesoft/active_presenter/tree/master

Second is just to use fiels_for

<% form_for @user do |f| %>

   <%=f.label :name %>
   <%=f.text_field :name %>

   <% fields_for @address do |fa| %>
      <%=fa.label :city %>
      <%=fa.text_field :city %>
   <% end %>

<% end %>

Then in the controller, save the records.

 @user = User.new(params[:user] 
 @address = Address.new(params[:address]

ActivePresenter works so well though.

Also found this via Google, which would work well.

http://railsforum.com/viewtopic.php?id=717

Brian Hogan
Second option seems very straightforward (I should've guessed it)I did come across that tutorial, but it is for nested models though.One question: what if I had multiple addresses?
I really recommend avoiding this if you can. It's not very pleasing to the user at all. If you simply must, then take a look at this first: http://blog.new-bamboo.co.uk/2007/8/31/presenters-conductors-on-railsYou can also use form arrays, but that's not something I can explain in a comment, and it's abstract.
Brian Hogan
avoiding adding multiple addresses you mean?that was just an example, I am not going to do it. but there may be cases where it'll be needed. for example, when the user is entering his interests (just as an example, cant think of anything better) one each per text field.
well then it's the same as adding multiple tasks. Post it as another question and I can try to answer that. I can't format code in the comments.
Brian Hogan
thanks Brian, added a separate questionhttp://stackoverflow.com/questions/894059/best-practices-for-multiple-models-in-rails-from-nested-non-nested-and-valid