Andru1989
Andru1989

Reputation: 180

undefined method in link to parent model

At this time I have this database structure

enter image description here

the configuration in routes.rb is like this

resources :polls do
    resources :subpolls
end

resources :subpolls do
    resources :preguntas
end

resources :preguntas do
    resources :respuestas
end

at this moment I'm in the "respuestas" model in index.html.erb file, and I Want a link_to called "back" to go back to preguntas model, so I have it this way

index.html.erb

<% link_to "Back", subpolls_preguntas_path(@preguntas.subpoll_id) , class: "btn btn-default btn-sm" %>

But I got this error

undefined method `subpoll_id' for nil:NilClass

The relations in models are ok

Can somebody tell me please how to fix it.

Upvotes: 0

Views: 97

Answers (2)

nickcen
nickcen

Reputation: 1692

as you are in the respuestas model and in the index page, so you may reference the parent object as @pregunta and not @preguntas

Upvotes: 1

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Simply read the exception message:

undefined method `subpoll_id' for nil:NilClass

When you do @preguntas.subpoll_id, ruby tells you that it can't call the methode subpoll_id on nil.

You have to initialize @preguntas as an instance of your Pregunta model.

Upvotes: 0

Related Questions