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 开发者_C百科should write this, please let me know.. Thanks in advance
You can do it the slow way:
YourModelClass.find(:all, :conditions => { :card_id => 5 }).count
or the fast way:
YourModelClass.count(:conditions => { :card_id => 5 })
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:
YourModelClass.where(:card_id => 5).count
That does a select count(*) from t where card_id = 5
inside the database. Don't use this one though:
YourModelClass.count(:card_id => 5)
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
LineItem.count(:conditions => {:cart_id => 5})
since i don't really know what's the model name, and the association... hope this helps =)
精彩评论