Add Badges with Item Count to my Navbar using Rails 3.2

1.1k Views Asked by At

I am looking for guidance/examples on the best way to add a badge to my <ul class = "nav navbar-nav">

I would like this badge to display the Item Count for all of the projects on the page.

views/projects/index.html.erb

<& @projects.each do | project | %>

views/layouts/_header.html.erb

<nav class="navbar navbar-inverse navbar-default" role="navigation">
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="active"><%= link_to "Projects", projects_path %> <span class="badge">(current)</span></li>

I realize I will probably need a "total" variable for the projects.item_count.

Then I probably want to put that 'projects.total variable next to <span class = "badge">projects.total</span>

Looking for the proper/best way to go about all of this.

1

There are 1 best solutions below

5
On BEST ANSWER

Added:

To get the total number of records for a model you simply call .count on the model class.

irb(main):004:0> User.count
   (0.8ms)  SELECT COUNT(*) FROM "users"
=> 1

However this cannot be used on an association since the associated objects belong to an instance - not to the class. So Project.items.count does not work but Item.count does. The same applies to collections ( @projects.items.count # error).

If you need the count of items for a project:

The simplest way would be to do:

<span class="badge"><%= project.items.size %></span>

We use .size instead of .length or .count since it is smart in that it will not cause an additional SQL query if the items already have been loaded.

Note that project is an instance of Project.

If you intend to use the items on another area in your view you can use this with a .joins or .includes query.

@products = Product.joins(:items).all

if you are not using the items...

If they are not loaded it will cause one extra SQL query per project. To avoid this you can use what are called counter caches.

class Item < ActiveRecord::Base
  belongs_to :project, counter_cache: true
end

Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. http://guides.rubyonrails.org/association_basics.html

You can create the column with the following migration:

$ rails g migration AddItemsCountToProjects items_count:integer