Topic: Form for Nested Model

I am brand new to Ruby on Rails so please forgive obvious Newbie questions.

My models are as follows.

class Client < ActiveRecord::Base
  attr_accessible :active, :comments, :name
  has_many :departments, :dependent => :destroy
  has_many :tasks, :through => :departments 

class Department < ActiveRecord::Base
  belongs_to :client
  has_many :tasks
  attr_accessible :department_manager, :department_name
class Tasks < ActiveRecord::Base
  belongs_to :department
  has_one :client, :through => :department
  attr_accessible :name

My routing is

Risk::Application.routes.draw do
  resources :clients do
    resources :departments do
      resources :tasks  

I am trying to create the ability to show a single department and add a task to that department and therefore the client. However, my efforts constantly result in errors such as "undefined method `model_name' for NilClass:Class"

I am looking for some guidance on the method with with to do this. Again. Very new to this, just trying to pick up some

Thanks for any help you could provide.

Re: Form for Nested Model

You should look at accepts_nested_attributes_for

Specifically also look at the section involving using accepts_nested_attributes_for with attr_accessible.

Re: Form for Nested Model

I looked through this but I am not sure if its the best way to solve my problem.

I am building an app that will have 4 levels of nested routes. Or at least of relationships.

Clients will have many departments, departments will have many tasks, and tasks will have many attributes.

I have 2 problems I am encountering.

1.) If I nest them as follows

resources :client do
  resources :department do
    resources :task do
      resouces :attributes 

I am struggling with how I would create a form for the Task and Attributes table.

Client and department I can handle though perhaps I just have a weak understanding of the workings of form_for (i expect this is true anyway.)

This is an example of a create method in my task controller

def create
  @department = @client.departments.find(params[:department_id])
  @task = @department.create(params[:task])

and here is an example of the form I am trying to use.

<%= form_for([@client,@department,@task])  do |f| %>
<% end%>

Alternatively I have tried nesting the objects shallowly or only 2 deep. But then the issue occurs where if I go from

if I try and link back to /clients/1/departments I don't have a :client_id anymore and cannot do this.

Just trying to learn and have spent a lot of time reading about the issue but can't seem to find a good resolution as of yet.