Never been to DZone Snippets before?

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) (See related posts)

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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts