I have to compare a table with candidates and a table with jobs, both tables has the field "skills", I want to see what job matches better with what worker, (the more skills in common, best fit).
I've tried to use arrays intersection, and create auxiliary tables like skills_worker and skill_jobs, but don't find the way to make it work.
Some help? Please?
CodePudding user response:
Newcomers to Rails seem to often create array columns where another table is better design. Your app is an example of where a skills table is suggested. You will need to create in a migration the skill_workers table, with integer fields worker_id and skill_id, and the job_skills table, with integer fields job_id and skill_id.
# app/models/job.rb
class job < ApplicationRecord
has_many :job_skills, dependent: :destroy
has_many :skills, through: :job_skills
end
# app/models/worker.rb
class Worker < ApplicationRecord
has_many :worker_skills, dependent: :destroy
has_many :skills, through: :worker_skills
end
# app/models/skill.rb
class Skill < ApplicationRecord
has_many :skill_workers, dependent: :destroy
has_many :workers, through: :skill_workers
has_many :job_skills, dependent: :destroy
has_many :jobs, through: :job_skills
end
With these tables populated, we ask the question "for a given worker, which job has the most matching skills".
worker = Worker.find(name: "Barney")
jobs = worker.skills.map(&:jobs).map(&:id) #=> [[3,9,22..],[3,18,22..],[18,28,53], ...]
# which of the job ids appears most often?
tally = jobs.flatten.tally #=> {1 => 1, 3 => 2, 22=> 3, ...} # count of each job id
best_fit_id = tally.invert.sort.last[1] # that's the job id that has the most skills in common