views:

121

answers:

1

I have two models:

class Employee < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  acts_as_taggable_on :skills, :roles
end

I would like to find Employees using the tags associated with their projects. The geokit-rails plugin supports a similar concept, using its ':through' relationship.

Ideally, I would be able to:

  • specify which tags (i.e. skills, roles) would be included in the conditions
  • order the employees by the total number of projects with matching tags
  • be able to access the matching-tag count for each employee for the purposes of building a tag cloud

Any thoughts would be appreciated.

A: 

I'm not sure the acts-as-taggable-on has support for what you looking for directly. However, you might be able to get at what you want knowing that the acts_as_taggable_on method adds two has_many relationships to your Project model. For example, to find employees where the project's skills has some tags you can write

Employee.all(:joins => {:projects => :taggings}, :conditions => ['taggings.context = ? and taggings.tag_id in (?)', 'skills', [4, 8, 15, 16, 23, 42])

Of course that requires knowing the tag ids you are interested in, instead if you have the tag names then

Employee.all(:joins => {:projects => :base_tags}, :conditions => ['taggings.context = ? and tags.name in (?)', 'skills', ['skill_a', 'skill_b', 'skill_c'])

You might be able to expand that to do the different counts you are looking for as well.

Corey
Perhaps I'm making a mistake, but executing ee=Employee.all(:joins => {:projects => :base_tags}, :conditions => ['taggings.context = ? and tags.name in (?)', 'skills', 'oracle']) at the IRB doesn't return anyhting: no errors, no employees, no messages. This should match a few projects. I'm also matching the case of the tag name ('skills') and the search value ('oracle'), if that is relevant. What am I missing?
Craig
This query gives me one Profile record for each matching Project (e.g. if two Projects for a Profile match a tag, you get that Profile repeated twice), rather than a unique list of Profiles that contain a matching Project. It's a good starting point, however. What I need is an EXISTS or IN query.
Craig