I currently have two models School and Course where School has_many courses, and Course belongs_to school. Additionally, School and Course are nested resources, where School is the parent resource, and Course the child.
I have created several test records in the Rails Console so that a query such as when the child calls upon the parent Course.first.school successfully executes and returns all the relevant information of the school Course.first is associated with.
However, when put into a controller function, I would instead get an error “undefined method `school’ for nil:NilClass” for the following line:
redirect_to school_course_path(@course.school, @course)
.. as if the .school part wasn’t recognized (where as it was in the console). Why is this the case, and how do I get past this error? Thanks!
Edit – as suggested, it could be that my @course instance variable isn’t passed from method to method in the controller. I have attempted at passing them through via a private method, but its still giving me the same error. Here is my code (background: the model Question belongs_to Course, with Course having many questions. Course isn’t part of the nested routes)
class QuestionsController < ApplicationController
def new
@course = Course.find(params[:course]) #confirmed working
self.current_course = @course #I attempt to set current_course, a private method
@question = Question.new
end
def create
@question = Question.new(params[:question]) #also works, in rails console all the questions confirms to have rails id
if @question.save
redirect_to school_course_path(current_course.school, current_course) #source of my frustrations - continues to returns same error message
else
render 'new'
end
end
private
def current_course=(course)
@current_school = course
end
def current_course
@current_course
end
end
Should work if your relationships are set up the way I think they are: