如何在 ActiveRecord 中找到完成百分比?
我似乎找不到一种优雅的方法来做到这一点。
但假设我的模型 Projects
有许多 Tasks
。
每个任务
都有一个表示完成
的布尔字段。
因此,如果我有 10 个任务,其中 4 个任务“完成”,6 个任务未完成,那么我只完成了 40%。
是否有一种巧妙的方法可以在范围
中执行此操作,以便 SQL 精简?
我已经有两个范围,例如:
scope :complete, lambda {
where("tasks.complete = true")
}
scope :not_complete, lambda {
where("tasks.complete = false")
}
感谢您的任何提示。
I can't seem to find an elegant way of doing this.
But let's say my model Projects
has many Tasks
.
Each task
has a boolean field for complete
.
So if I have 10 tasks
and 4 are "complete" and 6 are not, then I am only 40% complete.
Is there a slick way of doing this in a scope
so that the SQL is lean?
I already have two scopes like:
scope :complete, lambda {
where("tasks.complete = true")
}
scope :not_complete, lambda {
where("tasks.complete = false")
}
Thanks for any tips.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为,既然您希望从中获得最终价值,模型方法将是最好的方法。 (作用域应该返回一个关系以支持链接)您可以使用这些作用域返回完成百分比,类似于:
或者如果您在模型中需要 big_decimal 和 big_decimail/util ,您可以使用 to_d 来获得十进制除法。那么在你看来你所要做的就是@project.percent_complete
I would think that since you're looking to get a final value out of this a model method would be the best approach. (scopes should return a Relation in order to support chaining) You could use these scopes to return the percent complete, something along the lines of:
Or if you require big_decimal and big_decimail/util in your model you could use to_d to get decimal division. Then in your view all you have to do is @project.percent_complete