steven_noble
steven_noble

Reputation: 4203

What's causing this "undefined method `model_name' for NilClass:Class" error?

I have...

rake routes:

edit_report_question
GET
/reports/:report_id/questions/:id/edit(.:format)
questions#edit

questions_controller.rb:

  def edit
    @report = Report.find(params[:report_id])
    @questions = @report.questions.find(params[:id])
  end

report.rb:

has_many :questions

question.rb:

belongs_to :report

edit.html.haml:

.textbox
  = render "shared/notice"
  %h1 Edit Question
  = render "form"
  = render "actions"

_form.html.haml:

= simple_form_for [@report, @question] do |f|
  = f.error_notification
  = f.association :report
  = f.input :description
  = f.input :blueprint_name, :label => "Blueprint Name"
  = f.input :blueprint_url, :label => "Blueprint URL"
  = f.association :element, :label => "Website Element"
  = f.association :standard
  - if params[:action]=~ /edit/
    = f.association :fields, :as => :select
  = f.button :submit, :id => 'submit_question'

params:

{"action"=>"edit", "controller"=>"questions", "report_id"=>"1", "id"=>"1"}

Why then am I getting a "undefined method `model_name' for NilClass:Class" error?

Note: at present each report has many questions, but eventually I want reports to have many and belong to many questions.

Upvotes: 1

Views: 199

Answers (2)

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

You have not defined '@question' anywhere in the controller, i think your controller action should be like

def edit
  @report   = Report.find(params[:report_id])
  @question = @report.questions.find(params[:id]) # replacing @questions with @question
end

You are getting nil class error because @questions is an instance variable and don't have anything in it. Plus please try to dig out before posting. Thanks

Upvotes: 2

jvnill
jvnill

Reputation: 29599

the line that's causing the error is this line

simple_form_for [@report, @question]

since in the controller, you dont have @question variable, Rails can't infer the path of the form. I think @questions there should be @question

@questions = @report.questions.find(params[:id])

Upvotes: 1

Related Questions