【问题标题】:Iterate over an array in ruby遍历 ruby​​ 中的数组
【发布时间】:2020-05-03 19:50:06
【问题描述】:

我有多个 ID 的数组,如下所示。我想循环获取单个值。我在想这样的事情。

def letter(billing_ids)
 @billings = Billing.find(billings_ids.split(","))
 @billings.each do |bill|
  puts "#{bill}" 
 end
end

但我收到一个错误 ActiveRecord::RecordNotFound: 找不到所有带有 'id': ([66, 68]) 的比林斯(找到 1 个结果,但正在寻找 2 个)

ActiveRecord::RecordNotFound:找不到 'id'=[47] 的发票

我从这个查询中得到下面的数组 -

Office.all.each do |office|
  billing_ids=[] #initialize array
  office.issues.where("issues.amount > 0").each do |issue|
    billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.id
  end
  puts (billing_ids)
end

[66, 68]
[47]

请帮我弄清楚我该怎么做。

更新

def letter(billing_ids)
 @billings = Billing.where(id: billings_ids.split(","))
 @billings.each do |bill|
  puts "#{bill}" 
 end
end

更新 2:

def letter(billing_ids)
 puts "#{billing_ids}"
end

终端输出

 [66, 68]
 [47] 

更新 3

使用 byebug 找出问题所在,这就是我这样做时可以找到的内容

@billings = Billing.where(id: billing_ids) 
@billings.each do |bill| 
 byebug 
 puts bill.id
end

MethodError 异常:“[66, 68]”的未定义方法 `each':String

【问题讨论】:

  • find 如果找不到给定的记录,则会爆炸并引发异常。对于更柔和的方法:where(id: billing_ids.split(','))
  • 如果您正在获取第二段代码的输出,那么它应该已经是一个数组,split(',') 部分没有意义。
  • @tadman 请检查问题中的更新。如何从循环中访问 id?
  • 如果你已经加载了Billing 实例,那么bill.id 将是任何给定Billing 对象的ID。
  • @tadman 请查看问题中的更新 3

标签: ruby-on-rails ruby iteration


【解决方案1】:

您不需要拆分。
Ruby 范围接受数组:

 @billings = Billing.where(id: billings_ids)

【讨论】:

  • 如何遍历 billings 以获得 id?
  • def letter(billing_ids) @billings = Billing.where(id: billings_ids) @billings.each do |bill| puts "#{bill.id}" end end 它只显示 68。它不打印 66 和 47
  • 如果我在 def letter(billing_ids) puts "#{billing_ids}" 之后就放了,那么它会显示 [66, 68] [47]
  • 你调用 letter-function 的部分在哪里?
  • 抱歉,您问的是哪一部分?
【解决方案2】:

JSON.parse(billing_ids).each{|bill| bill} 解决了我的问题

【讨论】:

    【解决方案3】:

    请试试这个..它会工作的

    @billings = Billing.where(id: billing_ids) @billings.scan(/\d+/).map(&:to_i).each do |bill| byebug puts bill.id end

    .scan(/\d+/).map(&amp;:to_i)这会将字符串转换为整数数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 2015-09-26
      • 2014-11-21
      • 2012-06-07
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多