简体   繁体   中英

NoMethodError (undefined method `each' for nil:NilClass):

class Api::SurveyAnswersController < ApplicationController

  def create
    # @survey_answer = SurveyAnswer.new(survey_answer_params)
    survey_answers = []
    survey_id = params[:survey_id]
    params[:questions].each do |q|
      answer = {survey_id: survey_id, option_ids: [], question_id: q[:id], 
                title: q[:answer]}
      if q[:options].present?
        selected_options = q[:answer].split(',')
        selected_options.each do |selected_option|
          q[:options].each do |option|
            if option[:title]== selected_option
              answer[:option_ids] << option[:id]
              #<todo add break when in this condition
            end
          end
        end
        survey_answers << answer
      end
    end

    puts survey_answers
    # @survey_answers = SurveyAnswer.create(survey_answers)
    if SurveyAnswer.create(survey_answers)
    render json: survey_answers
    end
  end
end

I have a survey model which has some questions. Each question contains answers. When I try to hit post request through postman to insert answers, it gives 505 internal server error with message "undefined method each for nil:nilclass". Can anybody tell what the problem is?

You are trying to run the .each loop an empty object.

Make sure that both

params[:questions]

and

q[:options]

are not empty (not equal to nil ).

NoMethodError sometimes sounds very unrepresentative, especially if you're just starting off with Ruby.

Try to browse Stackoverflow next time, because this has been answered here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM