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
@projectvariable in the create action? - Tomáš Dundáček