David16
David16

Reputation: 11

Ruby on Rails complex search through foreign keys

Hi in my application I'm trying to search for an employee based on the skills. I have 3 classes involved Employee, Employee_skills and Skills

Could anyone point me in the direction of how to go about this search as everything I've tried returned errors. Here are their modals.

Employee

class Employee < ActiveRecord::Base
has_secure_password

has_many :employee_events
has_many :employee_skills , :class_name => EmployeeSkill, :foreign_key => "employee_id"
has_many :employee_projects
has_many :equipments
has_many :time_entry

has_one :holiday 
has_one :role
has_one :skill
has_one :tax

accepts_nested_attributes_for :skill


  validates :email, :presence => true, :uniqueness => true
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  def self.search(search)
  if search
    where('empLastName LIKE ?', "%#{search}%")
  else
    where(:all)
  end
end


  end

Employee_skills

class EmployeeSkill < ActiveRecord::Base

belongs_to :employee, :class_name => Employee, :foreign_key => "employee_id"
belongs_to :project
belongs_to :skill, :class_name => Skill, :foreign_key => "skill_id"

end

Skills

class Skill < ActiveRecord::Base

has_many :employee_skills

def self.search(search)
  where("skillType LIKE ?", "%#{search}%")
end

end

Upvotes: 0

Views: 61

Answers (2)

Vasili
Vasili

Reputation: 905

First of all, no need to specify class_name or foreign_key, because belongs_to :employee already refers to class Employee and foreign key employee_id.

And you could use has_and_belongs_to_many association, which is right for your needs: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

class Employee < ActiveRecord::Base
  has_and_belongs_to_many :skills
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :employees
end

And the migration:

class CreateEmployeesSkills < ActiveRecord::Migration
  create_table :employees_skills, id: false do |t|
    t.belongs_to :employee, index: true
    t.belongs_to :skill, index: true
  end
end

Upvotes: 0

gates
gates

Reputation: 4593

I think your situation is a good candidate for has_many_through association

class Employee < ActiveRecord::Base
 has_many :employee_skills
 has_many :skills, through: :employee_skills
end

class EmployeeSkills < ActiveRecord::Base
 belongs_to :employee
 belongs_to :skills
end

class Skill < ActiveRecord::Base
 has_many :employee_skills
 has_many :employees, through: :employee_skills
end

Now simply do

Skill.first.employees

Upvotes: 1

Related Questions