19

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 Answers 2

25

Two options:

First is ActivePresenter which works well for this.

Second is just to use fields_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 a railsforum post via Google, which would work well.

Sign up to request clarification or add additional context in comments.

5 Comments

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: blog.new-bamboo.co.uk/2007/8/31/presenters-conductors-on-rails You can also use form arrays, but that's not something I can explain in a comment, and it's abstract.
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.
thanks Brian, added a separate question stackoverflow.com/questions/894059/…
0

You can refer this tutorial by The Pragmatic Programmers

Advanced Rails Recipes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.