0

我正在运行此查询,并且在put上出现错误TypeError: no implicit conversion of String into Integer if I just try to get the ID from the array。

puts billing_ids然后输出是[<Billing id: 66, date: "2019-11-31", created_at: "2019-04-22 22:28:23", updated_at: "2020-01-15 17:03:05">]

如果我确实将 "#{billing_ids["id"]}"用于获取 id,那么我会收到错误TypeError: no implicit conversion of String into Integer

请帮我弄清楚如何获得ID。

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 #add id to array
  end
  puts "#{billing_ids["id"]}"
end

输出

[#<Billing id: 66, date: "2019-11-31", created_at: "2019-04-22 22:28:23", updated_at: "2020-01-15 17:03:05">]
4

3 回答 3

2

看起来您正在尝试打印数组中对象的 ID。

尝试这个:puts "{billing_ids.map(&:id)}"

关于错误TypeError: no implicit conversion of String into Integer

该错误是因为您要访问ArrayBilling 对象的索引“id”。id可以获取特定对象的属性,但是如果您尝试访问idArray,那将无法正常工作。(注意billing_ids是根据您的代码的数组)。数组可以通过整数索引访问(不像Hash

于 2020-01-16T05:17:18.810 回答
0

您需要billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.id将此行更改为billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.billing.idORbilling_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.pluck(:id)

于 2020-01-16T08:37:45.967 回答
0

您将 billing_ids 初始化为一个空数组,然后将一个计费模型 ID(一个 int)推入其中。如果您执行 billing_ids.first 您将获得您正在获取的 ID:issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.id

所以试试puts "#{billing_ids.first}"。这应该得到你的身份证。

注意:<<操作符 append——将给定的对象推到数组的末尾,并且由于您将 ID(而不是计费模型)推入 billing_ids,因此您无法访问 ID 的模型属性 ['ID']。

于 2020-01-16T05:15:51.740 回答