Over a million developers have joined DZone.

Submitting Data To Two Different Tables With Two Different Models (or How To Modify Multiple Models From One Form)

Taken from Norman Timmler's example on the ruby on rails mailing list.

Take two text fields for example:

# view
<%= form_tag :controller => :posts, :action => create %>
 <%= text_field("post", "title", "size" => 20) %>
 <%= text_field("user", "email", "size" => 20) %>
<%= end_form_tag %>

# posts_controller
class PostsController < ApplicationController
 def create
   @post = Post.create(params[:post])
   @user = User.create(params[:user])
   @post.users << @user

In the controller the params hash has one key for every object (user,
post) in your form. As a values of this key you find a hash having a
key-value pair for every object attribute (title, email).

This way you can submit multiple objects via one form.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}