Leahcim
Leahcim

Reputation: 41919

Rails - instance variable nil object in view

I'm working with some basic Rails scaffolding and know that instance variables are often used in the view to display data passed from a controller.

In my app, there's a few sample users in the database (which I can pull up in console using results = Result.all)

In my results_controller file, the index action also has this code (generated automatically by rails)

@results = Result.all

so I wanted to find out and display how many users there are at the top of NEW.html.erb (not in index.html.erb) so I put this

<%= @results.count %>

in views/results/NEW.html.erb but it gave me an error message about a nil object. Can you explain?

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.count

However, if I put this

<%= @results.count %>

in INDEX.html.erb, it shows the number...

NOTE: the purpose of doing this was the following: on new.html.erb, I had a form for users to enter some simple information. I was using planning on using <%= @results.count %> to tell users on that page how many people had already submitted info...

If you can't answer this stackoverflow question, can you explain another way to achieve the same effect?

Upvotes: 0

Views: 2157

Answers (1)

adimitri
adimitri

Reputation: 1296

It's not specified in the question so please forgive me if you've already done this. But the instance variable needs to be declared in the method that relates to the action that your currently accessing. In this case, it's the new action. So you should have code that looks something like this:

def new
  @result = Result.new
  @results = Result.all
end

You could also substitute the @results instance method for:

@results_count = Result.count

Upvotes: 1

Related Questions