0
votes

I've been going back and forth on this and can't work out why I'm getting an error with Rails 4!

I have 3 models, show below.

I'm try to create a section associated with a project and getting a NoMethodError of undefined method `sections' for nil:NilClass

From what I can tell, I'm going through the same process as when I create a project associated to a current_user.

Any help is greatly appreciated!

user.rb

class User < ActiveRecord::Base
   devise :invitable, :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
   has_many :projects
end

project.rb

class Project < ActiveRecord::Base
   belongs_to :user
   has_many :sections
 end

section.rb

class Section < ActiveRecord::Base
     belongs_to :project
end

routes.rb

Dr::Application.routes.draw do
  resources :projects do
    resources :sections
  end

  resources :sections

  root :to => "home#index"
  devise_for :users
end

sections_controller.rb

def new
  @section = Section.new
end

def create
  @project = params[:project_id]
  @section = @project.sections.build section_params
  respond_to do |format|
    if @section.save
      format.html { redirect_to project_path(@section), :notice => 'Section was successfully created.' }
      format.xml  { render :xml => @section, :status => :created, :location => @section }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @section.errors, :status => :unprocessable_entity }
    end
  end
end

private
def section_params
  params.require(:section).permit(:name)
end

new.html.haml

= simple_form_for [@project, @section] do |f|
  = f.input :name
  = f.button :submit
2
What is the content of your @project variable in the create action? - Tomáš Dundáček
@TomášDundáček I assumed I was doing that to pass the Project to the next line? - cupcakekid

2 Answers

1
votes

I think you should change the create action in your controller like following:

def create
  @project = current_user.projects.find(params[:project_id])
  @section = @project.sections.new section_params
  respond_to do |format|
    if @section.save
      format.html { redirect_to project_path(@project), :notice => "Section for #{@project.name} was successfully created." }
      format.xml  { render :xml => @project, :status => :created, :location => @section }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @section.errors, :status => :unprocessable_entity }
    end
  end
end
1
votes

for which project u have this form

= simple_form_for [@project, @section] do |f|
  = f.input :name
  = f.button :submit

i mean from where u are getting @project, if your form is in seperate view as u had said in new.html.haml then you new method must hhave @project also

def new
  @section = Section.new
  @project = current_user.projects.find(:id)  # pass an id for which u are creating section
end