How can I compare a BigDecimal with ActiveRecord decimal field?

拜拜、爱过 提交于 2019-12-05 21:03:13

Try using BigDecimal#round:

def load_bill_unless_exists(candidate)
  incumbents = Bill.scoped.where(:cost => candidate.cost.round(5))
  candidate.save unless incumbents.exists?
end

From the docs:

Round to the nearest 1 (by default), returning the result as a BigDecimal. If n is specified and positive, the fractional part of the result has no more than that many digits.

Given that you've specified a precision of 5 in your schema, that's what you should be rounding to when doing comparisons.

If casting like you were contemplating works, you probably have to go with that. The query you're using is just building a "WHERE cost = number" and if the database isn't able to compare properly with the number as passed, you need to pass it differently. It looks like it's the database stopping you and not anything within Rails necessarily.

If you just don't like casting within your query, you could always do it in the model:

def cost_with_incumbent_precision
  BigDecimal.new(cost.to_s, 18)
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!