I have an index view and action for a model called ReferralRequest. When I create the referral request, the create method in my controller renders the index, and in the index method I have @referral_requests = ReferralRequest.all.
For some reason, however, when I hit submit on the /new form and successfully create the referral request, I get a NoMethodError in ReferralRequests#create, an undefined method "each" in this line from the index view:
<% @referral_requests.each do |referral_request| %>
I can resolve this error by adding @referral_requests = ReferralRequest.all to my create method, but this seems wrong to me.
Can anyone figure out what is going on? Thanks for the feedback!
Here is my full referral requests controller:
class ReferralRequestsController < ApplicationController
before_action :require_login
def index
@referral_requests = ReferralRequest.all
end
def edit
@referral_request = ReferralRequest.find(params[:id])
end
def update
@referral_request = ReferralRequest.find(params[:id])
if @referral_request.update_attributes(referral_request_params)
flash[:success] = "Referral Request Updated!"
render 'referral_requests/index'
else
render "edit"
end
end
def create
@referral_request = current_user.referral_requests.build(referral_request_params)
if @referral_request.save
flash[:success] = "Referral Request Created!"
render 'referral_requests/index'
else
Rails.logger.info(@referral_request.errors.inspect)
@feed_items = []
render 'static_pages/home'
end
end
def destroy
end
def new
@patient = Patient.find(params[:patient_id])
@referral_request = current_user.referral_requests.build(patient: @patient) if signed_in?
end
def show
@referral_request = ReferralRequest.find(params[:id])
end
private
def referral_request_params
params.require(:referral_request).permit(:content, :patient_id, concern_ids: [],
insurance_ids: [], race_ids: [], language_ids: [], gender_ids: [])
end
end
change this line:
render 'referral_requests/index'
to:
redirect_to action: :index
as rendering the template itself does not invoke the controller action index, but the redirect will