简体   繁体   English

NoMethodError(nil:NilClass 的未定义方法 `each'):

[英]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".当我尝试通过邮递员点击发布请求以插入答案时,它给出了 505 内部服务器错误,并带有消息“每个 nil:nilclass 的未定义方法”。 Can anybody tell what the problem is?任何人都可以告诉问题是什么?

You are trying to run the .each loop an empty object.您正在尝试运行.each循环一个空对象。

Make sure that both确保两者

params[:questions]

and

q[:options]

are not empty (not equal to nil ).不为空(不等于nil )。

NoMethodError sometimes sounds very unrepresentative, especially if you're just starting off with Ruby. NoMethodError有时听起来很没有代表性,尤其是当您刚开始使用 Ruby 时。

Try to browse Stackoverflow next time, because this has been answered here .下次尝试浏览Stackoverflow,因为这里已经回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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