So, I'm a Rails newbie and may be missing something obvious, but I'm a bit flabbergasted as to why I'm getting a NoMethodError when I attempt to eager load an association using .includes.
Here's my code:
forecasts_controller.rb
def show
@forecast = Forecast.find(params[:id])
@forecast_projects = Project.includes(:project_type).where("forecast_id =?", params[:id])
end
_project.html.erb (this file is a collection partial rendered in the Forecast action)
<%= project.project_type.title %>
For some reason, this produces the following error:
NoMethodError in Forecasts#show
Showing /path where line #1 raised:
undefined method `title' for nil:NilClass
Oddly enough, if I change forecasts_controller.rb to...
def show
@forecast = Forecast.find(params[:id])
@forecast_projects = Project.joins(:project_type).where("forecast_id =?", params[:id])
end
Suddenly everything starts working perfectly. Can someone help me figure out what I'm missing here (and excuse my lack of experience)?