Search code examples
ruby-on-railsrails-activerecordrowcount

unable to determine row count Ruby-On-Rails


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


Solution

  • 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.