BigRon
BigRon

Reputation: 3282

Rails count vs. size model records when creating new record

I have a shopping cart in my Rails app. I am trying to display the number of items that are currently in the user's cart and update it asynchronously as the user adds items. I am displaying (and updating) this counter in the same controller action where you can create new cart items. The behavior is like this:

In the View

<%= link_to "#{current_user.cart_items.size} Items in Cart", cart_items_path, class: "btn btn-default" %>

In the Controller

def index
  @cart_item = current_user.cart_item.new # instantiate a new cart_item to be used in a form to create a new cart_item in this index action
end

So every time the View is loaded the current_user.cart_items.size count is one too many since the Action is instantiating a new cart_item.

I tried it out in the console to verify:

2.2.1 :022 > current_user.cart_items.size
 => 2 
2.2.1 :023 > current_user.cart_items.new
 => #<CartItem id: nil, user_id: 1, product_id: nil, created_at: nil, updated_at: nil> 
2.2.1 :024 > current_user.cart_items.size
 => 3

Is there any way to not count an object that is only instantiated an not yet saved?

Note: I tried this with build too in place of new and it had the same result.

Upvotes: 0

Views: 319

Answers (2)

Yann VERY
Yann VERY

Reputation: 1819

You can use count method instead of use size. For explanation, you need to know how size performs :

  • If a collection is loaded, the method will count elements in collection ( as an array )
  • If there is no loaded collection, the method perform a query.

In your situation, you want to perform a query as count method do : current_user.cart_items.count

Upvotes: 1

Yan Foto
Yan Foto

Reputation: 11388

Checkout new_record?:

Returns true if this object hasn't been saved yet – that is, a record for the object doesn't exist in the database yet; otherwise, returns false.

so in your case you'd have something like this:

@cart_item = current_user.cart_item.new
@cart_items.new_record? # false

Upvotes: 0

Related Questions