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.
<& @projects.each do | project | %>
<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.
Best How To :
To get the total number of records for a model you simply call
.count on the model class.
(0.8ms) SELECT COUNT(*) FROM "users"
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>
.size instead of
.count since it is smart in that it will not cause an additional SQL query if the items already have been loaded.
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
@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
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