ruby-on-railstagsacts-as-taggable-on

ActsAsTaggableOn: Get all tags for child objects in a has_many relation


My rails app has institution-level accounts with many users.

Each Institution has many Projects.

A project acts_as_taggable and users at an institution can add tags to their institution's projects.

I would like to query for a list of all tags on Projects belonging to a specific institution.

e.g., something like Project.where(institution_id: 1).tags (which doesn't exist)

Do I need to set the project's institution as the owner of the tags to facilitate this and then query by owner?

class Institution < ActiveRecord::Base
  acts_as_tagger
end

class Project < ActiveRecord::Base
  acts_as_taggable
end

Then when setting tags:

@current_user.institution.tag(@some_project, with: 'tag1, tag2')

...and getting the tags:

@current_user.institution.owned_tags

Or, is there an approach that does not require setting ownership?


Solution

  • Sure, do something like:

    ActsAsTaggableOn::Tag.
      joins(:taggings).
      where(taggings: {taggable: current_institution.projects})
    

    That syntax may require some tweaking (although, it works on my data).

    I am assuming you have some way to get the projects belonging to an institution - which I've sort of waved at with current_institution.projects. Substitute as appropriate for your own code.

    In any case, I believe that should head you in the right direction.