Searching Owner-Specific Tags in Rails with ActsAsTaggableOn and Ransack

Recently, I needed to implement a search feature for tags that are attached to specific owners using the acts_as_taggable_on gem in a Rails project. Since we use Ransack for searching, I wanted to integrate both tools. However, the standard documentation only covers searching tags without owners. If your tags are owner-specific, the default approach won’t work—so here’s how I solved it.
Here’s what I came up with:
class User < ActiveRecord::Base
acts_as_tagger
end
class Photo < ActiveRecord::Base
acts_as_taggable_on :locations
end
To add a new location tag to a photo, just use:
@some_user.tag(@some_photo, :with => "paris, normandy", :on => :locations)
This will create two records: one in the taggings table and one in the tags table.
To fetch the most recently added location tag for a photo:
Photo.last.taggings.last.tag.name
If you want to search for photos by location name, simply use:
taggings_tag_name_in: []
If your Photo model has multiple taggable contexts, you can specify the context as well:
taggings_context_eq: "locations"
So, your final Ransack query would look like this:
scope.ransack(taggings_tag_name_in: ["Barcelona"], taggings_context_eq: "locations").result
I hope this article helps you solve your tag-based search challenges with acts_as_taggable_on and Ransack. These gems are incredibly powerful when used together!



