Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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
 end
end


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.
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}