开发者

how to return a count of columns that are not null in rails

i'm trying to create a count for items in an order by taking the order row and counting the fields that are not null and returning this count as the nu开发者_如何学Cmber of items in the cart.

for example, for the order i have several columns across that store a specific item's id. so if that column has an item in it, there will be a product id stored in it. if not, it will be null.

the total number of fields in a row that are not null will be the total number of items in the cart for that order.

is there an easy way to use the count function in rails to accomplish this?


It would help if you included your model classes and schema, but here's a shot at counting how many items have the given order ID:

item_count = OrderItem.where(:order_id => order.id).count


The count method in ActiveRecord allows you to pass a :conditions option.

item_count = OrderItem.count(:conditions => "some_column IS NOT NULL")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜