User7777
User7777

Reputation: 299

TypeError: no implicit conversion of String into Integer in ruby

I am running this query and on puts I am getting an error TypeError: no implicit conversion of String into Integer if I just try to get the ID from the array.

puts billing_ids then the output is [<Billing id: 66, date: "2019-11-31", created_at: "2019-04-22 22:28:23", updated_at: "2020-01-15 17:03:05">]

And if I do puts "#{billing_ids["id"]}" to get just the id then I get the error TypeError: no implicit conversion of String into Integer

Please help me figure out how can I get the 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

Output

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

Upvotes: 0

Views: 2859

Answers (3)

Safwan S M
Safwan S M

Reputation: 123

you need to change billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.id this line to billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.billing.id OR billing_ids << issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.pluck(:id)

Upvotes: 0

Alok Swain
Alok Swain

Reputation: 6519

Looks like you are trying to print the ids of the objects which are in a Array.

Try this: puts "{billing_ids.map(&:id)}"

About the error TypeError: no implicit conversion of String into Integer

The error is because you are tring to access an index "id" of an Array of Billing objects. The id attribute of a particular object can be obtained but if you try accessing id of the Array, thats not going to work. (Note billing_ids is an Array as per your code). Array can be accessed by indices which are integers (unlike Hash)

Upvotes: 2

Javier Roque
Javier Roque

Reputation: 196

You are initializing billing_ids as an empty array and then pushing a billing model ID (an int) into it. If you do billing_ids.first you will then get the ID you're fetching in: issue.billings.where("billings.date < ?", Message.last.date).order(:date).last.id.

So try puts "#{billing_ids.first}". This should get your ID.

Note: the << operator appends—pushes the given object on to the end of the array, and since you are pushing an ID, not a billing model into billing_ids, you cannot access the model property ['ID'] of an ID.

Upvotes: 0

Related Questions