user85748
user85748

Reputation: 1213

how to handle multiple models in a rails form

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?

Upvotes: 19

Views: 13959

Answers (2)

Aravin
Aravin

Reputation: 7097

You can refer this tutorial by The Pragmatic Programmers

Advanced Rails Recipes

Upvotes: 0

Brian Hogan
Brian Hogan

Reputation: 3043

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.

Upvotes: 25

Related Questions