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.
Added:
To get the total number of records for a model you simply call
.count
on the model class.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 butItem.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:
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.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.
You can create the column with the following migration: