简体   繁体   中英

How to apply “to_f” to a column for all results in an active record query inside rails console

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} 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.

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

你可以这样尝试

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM