0

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?

3
  • Have you tried this under the same Rails environment (and database)? Commented Dec 1, 2011 at 3:19
  • yes, same app, same environment, same [email protected] works in index.html.erb but not in new.html.erb Commented Dec 1, 2011 at 3:20
  • Sounds like you also need @results = Result.all in the new action as well as the index action. Commented Dec 1, 2011 at 3:42

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.