Undefined method `id' for nil:Nilclass

Asked

Viewed 604 times

0

I’m a beginner in Ruby, and I made this mistake...

 def new
    @section = Section.new({:page_id => @page.id, :name => "Default"})
    @pages = @page.subject.pages.sorted
    @section_count = Section.count + 1
  end

Tell me the problem is on line two, someone can help me?

  • Apparently, @page is not initialized. Boot a puts @page at the very beginning of the method

  • continues to make the same mistake

  • Of course it will give the same error. I am interested in debugging to know what the value of @page. He hasn’t printed anything? How are you testing your code?

  • did not print anything, I am trying to access the page sections/new from the browser

  • You start the application from a terminal?

  • yes, but also not print anything on the terminal

  • Where would you like to see the information at @page? Who fills in this information for you to seek the id hers?

  • If possible, there are more details about the class created by you?

  • Ok, I confirmed here by reading several examples. When you call the new, your object is still empty. Therefore, @page has value nil. You need to pass as an argument new something he can start @page

Show 4 more comments

1 answer

1


It’s got a hell of a face to be a method new in a controller of a Rails application where @page would be being initialized somewhere out of of the method, probably in a before_action. If you don’t initialize @page with something, it is automatically initialized with nil and will give this error there. Search in your controller where you have some reference to @page that you will find (or not, if not there) your problem.

  • That’s right, if the error continues, create an if @page.present? before calling it, because what happens is that @page is an object, and it’s trying to call an attribute from an object that doesn’t exist, this generates an exception...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.