I’ve run into an error in my application, to explain the context: a user has several cars, each car can make a tanking therefore my TankingLogsController is the following
class TankingLogsController < ApplicationController
def new
@user = User.find(params[:user_id])
@car = @user.cars.find(params[:car_id])
@tankinglog = @cars.tanking_logs.build
end
end
This is my routes.rb file
Estaciones::Application.routes.draw do
root :to => "static_pages#home"
match '/contact', :to=>'static_pages#contact'
match '/about', :to=>'static_pages#about'
devise_for :users
resources :users do
resources :cars do
resources :tanking_logs
end
end
...
I encountered this error:
NoMethodError in TankingLogsController#new
undefined method `tanking_logs' for nil:NilClass
Application Trace | Framework Trace | Full Trace
app/controllers/tanking_logs_controller.rb:5:in `new'
Why is my application failing?
You have a very obvious error, and Ruby is telling you exactly what it is and where to find it.
You’ve written:
You initialize a variable called
@caron the first line, and you reference a second uninitialized variable@carson the second line.You have never initialized the
@carsvariable, so it is nil. Calling@cars.tanking_logscausesundefined method 'tanking_logs' for nil:NilClass, because you’re effectively writingnil.tanking_logs.The second line should be using
@car.tanking_logs.