MadEste
MadEste

Reputation: 110

Rails NoMethodError Undefined method in nested form

I am new to rails and am having trouble creating a new model within a nested form.

undefined method `days' for nil:NilClass

<%= form_for([@schedule, @schedule.days.build]) do |d| %>
    <%= d.label :date %><br/>
    <%= d.text_field :date %><br/>
    <%= d.submit %><br/>
<% end %>

My days controller looks like this :

class DaysController < ApplicationController
  def create
      @schedule = Schedule.find(params[:schedule_id])
      @day = @schedule.days.create(params[:day].permit(:date))
  end
end

And my Models are as follows:

class Day < ActiveRecord::Base
  belongs_to :schedule
end

class Schedule < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
  has_many :days, dependent: :destroy
  accepts_nested_attributes_for :days, allow_destroy: true
end

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :links, dependent: :destroy
  has_one :schedule, dependent: :destroy
  has_many :days, through: :schedule

  accepts_nested_attributes_for :links, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :schedule, allow_destroy: true   accepts_nested_attributes_for :days, allow_destroy: true

  validates :name, :description, presence: true
end

Also my routes:

Rails.application.routes.draw do

  devise_for :users
  resources :events do
      resources :schedules
  end

  resources :schedules do
    resources :days
  end

  root "page#home"
end

Upvotes: 1

Views: 1291

Answers (2)

gdpelican
gdpelican

Reputation: 568

You're defining @schedule in the create action, but the form is rendered after calling the new action, which means that @schedule is undefined at this point.

I'd try to stick to the rails convention of new/create, which looks something like

class DaysController
  def new
    @day = Schedule.find(params[:schedule_id]).days.new
  end

  def create
    @day = Day.new(params[:day])
    if @day.save
      redirect_to days_path # or wherever you want to go
    else
      render 'new'
    end
  end
end

To be clearer, the order of events is:

  • Call the days#new action by visiting the /schedule/:schedule_id/days/new route
  • The form is rendered
  • User inputs values and hits 'submit'
  • This calls the days#create action
  • The new Day is created based on the values the user put into the form.

Upvotes: 1

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

Where do you see the error ? For the action where the form is loaded or when you submit ?

If the error is during the action where the form is loaded, check if @schedule isn't nil.

If its on submit, then it may be a problem with your data or again debug to find out why @schedule is nil.

Simple way to test is to use rails console . Use the id in the URL

$ schedule = Schedule.find(3)
 # returns nil or the schedule object. if its nil then there is a problem with your data. 
$ schedule.days

Upvotes: 0

Related Questions