开发者

How can I find percent complete in ActiveRecord?

I can't seem to find an elegant way of doing this. 开发者_C百科

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.


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:

def percent_complete
  not_complete.size.to_f / complete.size.to_f
end

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜