Submitting Data To Two Different Tables With Two Different Models (or How To Modify Multiple Models From One Form)
Join the DZone community and get the full member experience.Join For Free
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 endIn 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.