Error using a nested resource 'undefined method' new 'for nil: NilClass'

0

I'm trying to make a nested resource work but I got stuck; I get an error trying to create a new 'prescription', please if someone can help me identify what is happening I would appreciate it.

Greetings!

Error:     undefined method 'new' for nil: NilClass

def new
  @prescription = @prescription.new
end

Routes:

Rails.application.routes.draw do

  resources :patients, shallow: true do
    resources :consultations do
      resources :prescriptions
    end 
  end
end

View from which '/ prescriptions / new' is generated

<%= link_to 'New Prescription', new_consultation_prescription_path(@consultation) %>
<%= link_to 'Show Prescriptions', consultation_prescriptions_path(@consultation) %> 

'Prescriptions' driver:

class PrescriptionsController < ApplicationController
  before_action :set_consultation
  before_action :set_prescription, only: [:show, :edit, :update, :destroy]

  def index
    @prescription = Prescriptions.all
  end

  def show
  end

  def new
    @prescription = @prescription.new
  end

  def edit
  end

  def create
    @prescription = @prescription.new(prescription_params)

    respond_to do |format|
      if @prescription.save
        format.html { redirect_to @prescription, notice: 'Prescription was successfully created.' }
        format.json { render :show, status: :created, location: @prescription }
      else
        format.html { render :new }
        format.json { render json: @prescription.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    def set_consultation
      @consultation = Consultation.find_by_id(params[:id])
    end

    def set_prescription
      @prescription = Prescription.find(params[:id])
    end

    def prescription_params
      params.require(:prescription).permit(:prescription, :consultation_id)
    end
end

Model 'Prescription':

class Prescription < ActiveRecord::Base
  belongs_to :consultation, :dependent => :destroy
end

Form 'Prescription':

<%= form_for([@consultation, @prescription]) do |f| %>
  <% if @prescription.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@prescription.errors.count, "error") %> prohibited this prescription from being saved:</h2>

      <ul>
      <% @prescription.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :prescription %><br>
    <%= f.text_area :prescription %>
  </div>
  <div class="field">
    <%= f.label :consultation_id %><br>
    <%= f.text_field :consultation_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
    
asked by Carlos Gómez 17.08.2016 в 19:30
source

1 answer

0

The way you use to initialize the prescription object is incorrect. It should be @prescription = Prescription.new

    
answered by 18.08.2016 в 03:18