无法确定行数 Ruby-On-Rails
我试图在 ruby on Rails 中构建一个购物车,它需要我显示如下输出:您的购物车中有 3 件商品(3 是我的购物车中的商品数量),我试图找到表中的行数line_items 其中 cart_id 为 5。
@line_items.find(:all, :condition => { :cart_id => "5"}).count
如果有人知道我应该如何写这个,请告诉我..提前致谢
im trying to build a cart in ruby on rails it requires me to show the output like this : You have 3 items in your cart (3 being the number of items in my cart) and im trying to find the number of rows in the table line_items where the cart_id is 5.
@line_items.find(:all, :condition => { :cart_id => "5"}).count
if anyone know how i should write this, please let me know.. Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以采用慢速方式:
或快速方式:
快速方式只是在数据库内执行
COUNT(*)
,慢速方式将整个结果集从数据库中拉出,将其转换为对象,然后对它们进行计数。还有现代 Rails3+ 方法:
在数据库内执行
select count(*) from t where card_id = 5
。但不要使用这个:这将执行
select count(card_id = 5) from t
,而这根本不像你想要的那样。You can do it the slow way:
or the fast way:
The fast way simply does a
COUNT(*)
inside the database, the slow way pulls the whole result set out of the database, turns it into objects, and then counts them.There's also the modern Rails3+ way:
That does a
select count(*) from t where card_id = 5
inside the database. Don't use this one though:That will do a
select count(card_id = 5) from t
and that's nothing at all like what you want.它应该是单独的东西,
因为我真的不知道模型名称是什么,以及关联......希望这有帮助=)
it should be something alone the line of
since i don't really know what's the model name, and the association... hope this helps =)