Really hoping someone on this forum can help me out - any help is
greatly appreciated.
I have been through the Ryan B railcasts and tutorials on using a
single form to update more than one model. They are all based on the
concept of having Project model that has many Tasks. The application
I am working on requires a third level of model added to the form so
Projec has many Tasks and Task has many Task Details. I can display
the form in the “new” action so that all fields show up and it appears
right. However, I can not get the “create” to work, not sure if the
problem is “create” in my controller, or the hash being created in my
fields_for tag.
class Project < ActiveRecord::Base
has_many :tasks
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
end
class Task < ActiveRecord::Base
has_many :task_details
belongs_to :projects
def task_detail_attributes=(task_detail_attributes)
task_detail_attributes.each do |attributes|
task_details.build(attributes)
end
end
end
class TaskDetail < ActiveRecord::Base
belongs_to :tasks
end
class ProjectController < ApplicationController
def index
@projects = Project.find(:all)
end
def new
@project = Project.new
@project.tasks.build
@task = Task.new
@task.task_details.build
end
def create
@project = Project.new(params[:project])
@task = Task.new(params[:task])
params[:task].each_value { |task_detail|
@task.task_details.build{task_detail} }
if @project.save and @task.save
flash[:notice] = “Successfully created project.”
render :action => ‘index’
else
render :action => ‘new’
end
end
end
<% form_for :project, :url => { :action => :create } do |f| %>
Name: <%= f.text_field :name %> Date: <%= f.date_select(:date) %>
<% for task in @project.tasks %> <% fields_for "project[task_attributes][]", task do |task_form| %>Name: <%= task_form.text_field :name %> Description: <%= task_form.text_area :description %> Fixed Task: <%= task_form.check_box :fixed_flg %>
<% end %><% for task_detail in @project.tasks %>
<% fields_for “task[task_detail_attributes][]”, task_detail do |
detail_form| %>
Sub Task: <%= detail_form.text_field :sub_task %>
Assigned: <%= detail_form.check_box :assigned_flg %>
<% end %>
<% end %>
<% end %>
<%= submit_tag "Create Project" %>
<% end %>