Permalink
Browse files

adding code from book

  • Loading branch information...
1 parent 65f95b2 commit e397c44f78df34e1a6ced390dc8ee521343fae2d @ryanb ryanb committed Jul 18, 2008
View
6 README
@@ -1,6 +1,6 @@
Complex Form Examples
---------------------
-Several different ways to handle the multi-model form problem with a
-one-to-many association. The various approaches are in git branches.
-See them for examples.
+This one is copied directly from the Advanced Rails Recipes book.
+
+http://www.pragprog.com/titles/fr_arr/advanced-rails-recipes
@@ -9,6 +9,7 @@ def show
def new
@project = Project.new
+ @project.tasks.build
end
def create
@@ -26,6 +27,7 @@ def edit
end
def update
+ params[:project][:existing_task_attributes] ||= {}
@project = Project.find(params[:id])
if @project.update_attributes(params[:project])
flash[:notice] = "Successfully updated project."
@@ -1,2 +1,7 @@
module ProjectsHelper
+ def add_task_link(name)
+ link_to_function name do |page|
+ page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
+ end
+ end
end
View
@@ -1,4 +1,31 @@
class Project < ActiveRecord::Base
- has_many :tasks
+ has_many :tasks, :dependent => :destroy
+
validates_presence_of :name
+ validates_associated :tasks
+
+ after_update :save_tasks
+
+ def new_task_attributes=(task_attributes)
+ task_attributes.each do |attributes|
+ tasks.build(attributes)
+ end
+ end
+
+ def existing_task_attributes=(task_attributes)
+ tasks.reject(&:new_record?).each do |task|
+ attributes = task_attributes[task.id.to_s]
+ if attributes
+ task.attributes = attributes
+ else
+ tasks.delete(task)
+ end
+ end
+ end
+
+ def save_tasks
+ tasks.each do |task|
+ task.save(false)
+ end
+ end
end
@@ -4,6 +4,7 @@
<head>
<title><%= h(yield(:title) || "Untitled") %></title>
<%= stylesheet_link_tag 'application' %>
+ <%= javascript_include_tag :defaults %>
<%= yield(:head) %>
</head>
<body>
@@ -1,8 +1,16 @@
<%= error_messages_for :project %>
-<% form_for @project do |f| %>
+
+<% form_for @project do |f| -%>
<p>
- <%= f.label :name %><br />
- <%= f.text_field :name %>
+ Name: <%= f.text_field :name %>
</p>
- <p><%= f.submit "Submit" %></p>
-<% end %>
+ <div id="tasks">
+ <%= render :partial => 'task', :collection => @project.tasks %>
+ </div>
+ <p>
+ <%= add_task_link "Add a task" %>
+ </p>
+ <p>
+ <%= f.submit "Submit" %>
+ </p>
+<% end -%>
@@ -0,0 +1,11 @@
+<div class="task">
+<% new_or_existing = task.new_record? ? 'new' : 'existing' %>
+<% prefix = "project[#{new_or_existing}_task_attributes][]" %>
+
+<% fields_for prefix, task do |task_form| -%>
+ <p>
+ Task: <%= task_form.text_field :name %>
+ <%= link_to_function "remove", "$(this).up('.task').remove()" %>
+ </p>
+<% end -%>
+</div>

0 comments on commit e397c44

Please sign in to comment.