如何将 BigDecimal 与 ActiveRecord 小数字段进行比较?
假设这样的模式:
create_table "bills", :force => true do |t|
t.decimal "cost", :precision => 10, :scale => 5
end
我想编写一个函数,将新账单写入数据库,前提是它是唯一的。以下内容不起作用:
def load_bill_unless_exists(candidate)
incumbents = Bill.scoped.where(:cost => candidate.cost)
candidate.save unless incumbents.exists?
end
因为现有法案和候选法案在 BigDecimal 表示中具有不同的限制,因此 :cost => Candidate.cost
测试失败。也就是说,它正在比较:
candidate: #<Bill id: nil, cost: #<BigDecimal:105e39850,'0.1670576666 6666666E4',27(27)>>
请
incumbent: #<ServiceBill id: 198449, cost: #<BigDecimal:105e35840,'0.167057667E4',18(18)>>
注意,候选人的 BigDecimal 表示的成本比现任者有更多的位数。
所以问题很简单:进行这种比较的正确方法是什么?我考虑了 :cost => BigDecimal.new(candidate.cost.to_s, 18)
,但这感觉不对——例如,数字 18 从哪里来?
Assume a schema like this:
create_table "bills", :force => true do |t|
t.decimal "cost", :precision => 10, :scale => 5
end
I want to write a function that writes a new bill to the DB iff it is unique. The following does not work:
def load_bill_unless_exists(candidate)
incumbents = Bill.scoped.where(:cost => candidate.cost)
candidate.save unless incumbents.exists?
end
because the incumbent bills and the candidate bills have different limits in their BigDecimal representation, so the :cost => candidate.cost
test fails. That is, it's comparing:
candidate: #<Bill id: nil, cost: #<BigDecimal:105e39850,'0.1670576666 6666666E4',27(27)>>
with
incumbent: #<ServiceBill id: 198449, cost: #<BigDecimal:105e35840,'0.167057667E4',18(18)>>
Notice the candidate's BigDecimal represents the cost with more digits than the incumbent.
So the question is simple: What's the right way to perform this comparison? I contemplated :cost => BigDecimal.new(candidate.cost.to_s, 18)
, but that doesn't feel right -- for example, where does that number 18 come from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 BigDecimal#round :
来自文档:
鉴于您在模式中指定了精度 5,这就是您在进行比较时应该舍入的值。
Try using
BigDecimal#round
:From the docs:
Given that you've specified a precision of 5 in your schema, that's what you should be rounding to when doing comparisons.
如果选角就像你正在考虑的那样有效,你可能必须这样做。您使用的查询只是构建一个“WHERE cost = number”,如果数据库无法与传递的数字正确比较,您需要以不同的方式传递它。看起来是数据库阻止了你,而不一定是 Rails 中的任何东西。
如果您只是不喜欢在查询中进行转换,则始终可以在模型中执行此操作:
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: