Skip to content
Richard Huang edited this page Aug 15, 2010 · 4 revisions

Please go to http://rails-bestpractices.com/posts/9-nested-model-forms

Before:


class Product < ActiveRecord::Base
  has_one :detail
end

class Detail < ActiveRecord::Base
  belongs_to :product
end

<% form_for :product do |f| %>
  <%= f.text_field :title %>
  <% fields_for :detail do |detail| %>
    <%= detail.text_field :manufacturer %>
  <% end %>
<% end %>

class ProductsController < ApplicationController

  def create
    @product = Product.new(params[:product])
    @detail = Detail.new(params[:detail])

    Product.transaction do
      @product.save!
      @detail.product = @product
      @detail.save
    end
  end

end

After: (one-to-one)


class Product < ActiveRecord::Base
  has_one :detail
  accepts_nested_attributes_for :detail
end

<% form_for :product do |f| %>
  <%= f.text_field :title %>
  <% f.fields_for :detail do |detail| %>
    <%= detail.text_field :manufacturer %>
  <% end %>
<% end %>

class ProductsController < ApplicationController

  def create
    @product = Product.new(params[:product])
    @product.save
  end

end

After: (one-to-many)


class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

<% form_for @project do |f| %>
  <%= f.text_field :name %>
  <% f.fields_for :tasks do |tasks_form| %>
    <%= tasks_form.text_field :name %>
  <% end %>
<% end %>