【问题标题】:How to increment the loop if it does not match the id?如果与 id 不匹配,如何增加循环?
【发布时间】:2018-02-06 13:26:30
【问题描述】:

我正在编写一个显示来自 AWS 服务器的图像的代码。但是我在循环代码时遇到了麻烦。

第一次显示效果很好,但不能更进一步(我最多显示 6 张图像)

代码 -

def get_image_urls(user)
        user_identifications = user.user_identifications.where(current_flag: true).order(:id_dl)
        urls = []
        keys = []
        if !user_identifications.empty? && !user_identifications.nil?
            user_identifications.each_with_index do |each_id, index|
                obj = S3_BUCKET.object(each_id.aws_key)
                urls << {each_id.id_dl=> obj.presigned_url(:get)}
                keys << {each_id.id_dl=> each_id.aws_key}
            end
        end
        return urls, keys
    end

如何根据 id 和 user.identifications 值增加循环?

【问题讨论】:

  • !user_identifications.empty? &amp;&amp; !user_identifications.nil?user_identifications.present?
  • 代码似乎没问题。 user_identifications 有多个值??
  • 是的。它总共有 6 个值。无论上传如何,我都想按顺序显示所有这些。所以我使用了一个标志。根据其状态,我想显示图像@AbibullahRahamathulah

标签: ruby-on-rails ruby-on-rails-3 amazon-s3


【解决方案1】:

reject所有空值然后迭代users_identifications。 喜欢:

sanitized_identifications = users_identifications.reject(&:blank?)
sanitized_identifications.each_with_index do |identification, _index|
  # Now if you want to skip an iteration based on some condition, try `next`, like:
  # next if some_condition
  # in you case
  obj = S3_BUCKET.object(each_id.aws_key)
  next if obj.blank?
  urls << {each_id.id_dl=> obj.presigned_url(:get)}
  keys << {each_id.id_dl=> each_id.aws_key}
end

更新

# ...
user_identifications.each_with_index do |each_id, index|
  begin
    obj = S3_BUCKET.object(each_id.aws_key)
    urls << {each_id.id_dl=> obj.presigned_url(:get)}
    keys << {each_id.id_dl=> each_id.aws_key}
  rescue => e
    next
  end
end
#...

干杯!

【讨论】:

  • 这与我正在处理的变量相同,只是对变量进行了一些更改。我正在寻找可以跳过空白字段并转到下一个字段的内容!
  • empty field 表示obj.empty?
  • 是的。有些字段可能没有任何内容,有些则有。这就是增量应该发生的地方,它将跳过空字段
  • 我之前已经提到过,无论如何我已经更新了我的答案。试试看:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2015-04-15
  • 2021-05-29
  • 2021-12-23
相关资源
最近更新 更多