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?

Answers


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

Need Your Help

Cleaning up HTML tag attributes

javascript regex html-parsing tag-soup

I need to wade through a lot of HTML using JavaScript to adjust the attribute quote syntax to be all double quotes. I don't need to worry about key-only attributes like "disabled" or "selected".

Multiple script/paperscripts in the same paperscope

paperjs

I'm starting with paper.js. I like the fact that it introduces the possibility to have a script with a text/paperscript mime type, which runs in its on scope. However, scripts can become large pretty

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.