I am using ActsAsTaggableOn
on my Item
model.
To get a list of all the items tagged with a particular tag, I have to do this:
Item.tagged_with("some_tag")
However, I am using this in a navigation partial to dynamically generate navigation of tags based on the amount of items in a tag. I want the 4 tags that have the highest number of items.
So I am doing this in my navigation
partial:
<% Item.tag_counts.order(:count).limit(4).each do |tag| %>
<% if params[:tag] == tag.name %>
<li class="active"><%= link_to tag.name.capitalize, tag_path(tag.name) %></li>
<% else %>
<li><%= link_to tag.name.capitalize, tag_path(tag.name) %></li>
<% end %>
<% end %>
However, when I only have say 2 or 3 items (i.e. any amount below 4 but greater than 1) and I have an item that has been tagged but not 'approved' (i.e. it doesn't show on the page until it has been approved by an admin and the flag is_approved
changes from false
to true
) the tag
shows up in this list (which is bad, I don't want it to show up when no items have been approved), but the item doesn't show up when you click the tag (which is good because it hasn't been approved).
How do I modify the each
statement to also accommodate items
that have been approved
?
The easiest way to determine if an Item
has been approved is like this:
item.is_approved?
Example:
> i
=> #<Item id: 17, name: "10pp-logo", link: "10pound.zip", description: "10PP Logo.<br><br>Full of graphical good...", price: 6.99, user_id: 1702, created_at: "2013-11-24 12:56:05", updated_at: "2013-11-24 12:56:05", image: "ten.png", is_approved: false, approved_at: nil>
> i.is_approved?
=> false
Edit 1:
> Item.tag_counts
(2.0ms) SELECT items.id FROM "items"
ActsAsTaggableOn::Tag Load (4.5ms) SELECT tags.*, taggings.tags_count AS count FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN items ON items.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Item' AND taggings.context = 'tags') AND (taggings.taggable_id IN(13,15,17)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
=> [#<ActsAsTaggableOn::Tag id: 6, name: "gmail">, #<ActsAsTaggableOn::Tag id: 11, name: "10pp">, #<ActsAsTaggableOn::Tag id: 4, name: "twitter">, #<ActsAsTaggableOn::Tag id: 5, name: "facebook">, #<ActsAsTaggableOn::Tag id: 8, name: "fitness">, #<ActsAsTaggableOn::Tag id: 1, name: "notepad">, #<ActsAsTaggableOn::Tag id: 2, name: "paper">, #<ActsAsTaggableOn::Tag id: 9, name: "logo">, #<ActsAsTaggableOn::Tag id: 7, name: "login form">]