繁体   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

我有一个调查模型,其中有一些问题。 每个问题都包含答案。 当我尝试通过邮递员点击发布请求以插入答案时,它给出了 505 内部服务器错误,并带有消息“每个 nil:nilclass 的未定义方法”。 任何人都可以告诉问题是什么?

您正在尝试运行.each循环一个空对象。

确保两者

params[:questions]

q[:options]

不为空(不等于nil )。

NoMethodError有时听起来很没有代表性,尤其是当您刚开始使用 Ruby 时。

下次尝试浏览Stackoverflow,因为这里已经回答

暂无
暂无

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

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