DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
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 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.