未定义的方法`每个' for nil:更新方法中的NilClass

时间:2016-05-26 11:38:02

标签: ruby-on-rails

我的ruby on rails应用程序中有一个奥迪模型,其中有许多字段,如模型,变体,汽车图像,外观,内饰,小册子等。当我尝试更新某些属性(不是全部)时,它会给出未定义的方法`每个'为零:外部和内部图像部分的NilClass。

更具体地说,问题在于:

params[:exterior_image].each { |exterior_image| ... }

更新方法:

def update
    respond_to do |format|
      @audi_model = AudiModel.find(params[:id])
      if @audi_model.update(audi_model_params)
            model_exterior_image_names = @audi_model.car_exterior_images.map{|m|m.exterior_image_file_name}
            params[:exterior_image].each { |exterior_image|
            unless model_exterior_image_names.include?(exterior_image.original_filename)
            @audi_model.car_exterior_images.create(exterior_image: exterior_image)
            end
            }
            model_interior_image_names = @audi_model.car_interior_images.map{|m|m.interior_image_file_name}
            params[:interior_image].each { |interior_image|
            unless model_interior_image_names.include?(interior_image.original_filename)
            @audi_model.car_interior_images.create(interior_image: interior_image)
            end
            }
        format.html { redirect_to @audi_model, notice: 'Audi model was successfully updated.' }
        format.json { render :show, status: :ok, location: @audi_model }
      else
        format.html { render :edit }
        format.json { render json: @audi_model.errors, status: :unprocessable_entity }
      end
    end

请求 参数:

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"3qiq/VNRNk369HEZr0Eb/R5iuhKgGTpJCfOh8ek3nGWLeU+zDNDvEAwJ3SvlLb0h4gVql549d3GnCV9Fa/ZnNA==",
 "audi_model"=>{"car_model"=>"TT",
 "variant"=>"Diesel",
 "introduction"=>"test",
 "engine"=>"test",
 "video_url"=>"https://www.youtube.com/watch?v=N3x_RZlOmK0",
 "brochure_url"=>"http://www.audigurgaon.in/brochure/tt-brochure-2014.pdf"},
 "commit"=>"Update Audi model",
 "id"=>"19"}

1 个答案:

答案 0 :(得分:1)

您的params没有:exterior_image密钥,因此会返回nil。您必须检查以确保params[:exterior_image]不是nil,然后才调用.each方法。

params[:exterior_image].each do |exterior_image|
    unless model_exterior_image_names.include?(exterior_image.original_filename)
        @audi_model.car_exterior_images.create(exterior_image: exterior_image)
    end
end if params[:exterior_image]

或者,给它一个空数组:

(params[:exterior_image] || []).each do |exterior_image|
    unless model_exterior_image_names.include?(exterior_image.original_filename)
        @audi_model.car_exterior_images.create(exterior_image: exterior_image)
    end
end