代码的一部分未在方法中执行

时间:2017-08-07 12:07:58

标签: ruby-on-rails ruby

我有一个ImageAnalyses控制器,我想在实例化 ImageAnalysis 之后但在保存@image_analysis之前执行一些代码。虽然控制器成功创建了ImageAnalysis的实例,但它没有执行下面的中间代码。

我的控制器:

#image_analyses_controller.rb

def create
 @image_analysis = ImageAnalysis.new(image_analysis_params)


 # Start of not executed code
 @client = Aws::Rekognition::Client.new
 @image_analysis.gallery.attachments do |attachment|
   resp = @client.detect_labels(
           image:
              { s3_object: {
                bucket: "my-bucket",
                name: attachment.content.path,
              },
            }
         )

   high_labels = resp.labels.select { |label| label.confidence > 80 }

   high_labels.each do |label|
    ImageLabel.create(
      name: label.name,
      image_url: attachment.content.path,
      image_analysis_id: @image_analysis.id
    )
   end
 end
 # End of not executed code

 respond_to do |format|
  if @image_analysis.save
    format.html { redirect_to @image_analysis, notice: 'Image analysis was successfully created.' }
    format.json { render :show, status: :created, location: @image_analysis }
  else
    format.html { render :new }
    format.json { render json: @image_analysis.errors, status: :unprocessable_entity }
  end
 end
end

有趣的是,没有引发异常,服务器日志只注册ImageAnalysis对象的创建,没有任何指向我的错误。

我试图将该块代码传递给模型中的方法,并从控制器调用它,但结果相同。你能告诉我为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

我认为您忘记了必须迭代.each的行中的@image_analysis.gallery.attachments

这样的事情:

 @image_analysis.gallery.attachments.each do |attachment|
   resp = @client.detect_labels(
           image:
              { s3_object: {
                bucket: "my-bucket",
                name: attachment.content.path,
              },
            }
         )

   high_labels = resp.labels.select { |label| label.confidence > 80 }

   high_labels.each do |label|
    ImageLabel.create(
      name: label.name,
      image_url: attachment.content.path,
      image_analysis_id: @image_analysis.id
    )
   end
 end

但是如果@image_analysis.gallery.attachments为空,则.each内的代码将不会被执行。