Estoy tratando de hacer funcionar un recurso anidado pero me quede atascado; obtengo un error al tratar de crear una nueva 'prescripcion', por favor si alguien puede ayudarme a identificar lo que esta sucediendo se lo agradecería.
Saludos!
Error: undefined method `new' for nil:NilClass
def new
@prescription = @prescription.new
end
Rutas:
Rails.application.routes.draw do
resources :patients, shallow: true do
resources :consultations do
resources :prescriptions
end
end
end
Vista desde la cual se genera '/prescriptions/new'
<%= link_to 'New Prescription', new_consultation_prescription_path(@consultation) %>
<%= link_to 'Show Prescriptions', consultation_prescriptions_path(@consultation) %>
Controlador 'Prescriptions':
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
Modelo '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 %>