1
votes

Here my models:

class Train < ApplicationRecord
  has_many :train_lines
end

class TrainLine < ApplicationRecord
  belongs_to :train
end

My controller:

# controllers/train_lines_controller.rb
class TrainLinesController < ApplicationController
  def index
    @train_lines = TrainLine.all
  end
end

And here my views:

# views/train_lines/index.html
<%=  render @train_lines %>

# views/train_lines/_train_line.html.erb
<p><%= train_line.train.id %></p>

I get undefined methodid' for nil:NilClass` error

If I run Rails console I can successfully call:

$ tl = TrainLine.first
$ tl.train.id
$ 6028

EDIT

It seems it renders something, and for some reason it breaks. I get the following in the log:

Rendered collection of train_lines/_train_line.html.erb [6197 times] (5875.4ms) Rendered train_lines/index.html.erb within layouts/application (5992.4ms) Completed 500 Internal Server Error in 6008ms (ActiveRecord: 1165.4ms)

ActionView::Template::Error (undefined method `id' for nil:NilClass): 1:

<%= train_line.train.id %>

Any clue?

1
Try @train_line.train.id. - hashrocket
Can't find declaration for @train_line - davideghz
You'll have to declare it in your controller. - hashrocket
Can you see a Rendered collection of ... in the server's log? - Sebastian Palma
I inspected the DB and I found out an empty line at the end of the table. It was causing the lookup on the foreign key to return null ;( wasted 2 hours of my life LOL - davideghz

1 Answers

1
votes

After inspecting the DB I found out an empty line at the end of the train_lines table. It was causing the lookup on the foreign key train_id to return null. Calling id on null stopped the render and caused the page not to load.