1

I have this query: p = Payment.where(:client_id => 1)

Then only some fields, so I execute this: p.select(:id, :created_at, :amount)

The issue is that every amount in the result comes as BigDecimal, and it's not readable. I need to apply to_f function inside rails console to have a readable set of results.

I tried map,like this: p.map {|p| p.amount.to_f} But it returns to me an array only with the amounts, and I need it to be along with the other attributes.

3 Answers3

1

To solve you problem and get all fields:

p.map { |i| [i.id, i.created_at, i.amount.to_f] }

Also you can take a look on this article. Maybe you just need float type for amount field in your DB

Peter Balaban
  • 653
  • 3
  • 7
1

You can try like this,

p.map { |item| { id: item.id, created_at: item.created_at, amount: item.amount.to_f}}
0

if you always want float of amount you can set callback after_find

class Payment < ActiveRecord::Base
  after_find do |payment|
    self.amount = self.amount.to_f
  end
end

it will always give you float value when you find object

  • It will not update value in your db.

Please Look on this Rails Callback

Ketan Mangukiya
  • 360
  • 1
  • 7
  • I need to do this inside the rails console. That seems a lot of code to put in the console, compared with `https://stackoverflow.com/users/5954643/rajkumar-ulaganadhan` solution. Thanks anyway. – Ricardo Gamarra May 29 '19 at 15:29
  • it will work on your console too, i mean you will get same output. – Ketan Mangukiya May 29 '19 at 17:47