繁体   English   中英

Ruby on Rails通过外键进行复杂搜索

[英]Ruby on Rails complex search through foreign keys

您好我的应用程序中,我试图根据技能来寻找一名雇员。 我有3个课程,涉及Employee,Employee_skills和Skills

任何人都可以指出我该进行此搜索的方向,因为我尝试过的所有操作都返回了错误。 这是他们的模态。

雇员

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

员工技能

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

技能专长

class Skill < ActiveRecord::Base

has_many :employee_skills

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

end

我认为您的情况非常适合has_many_through协会

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

现在简单地做

Skill.first.employees

首先,无需指定class_nameforeign_key ,因为belongs_to :employee已经引用了类Employee和外键employee_id

您可以使用has_and_belongs_to_many您需要的has_and_belongs_to_many关联: http : has_and_belongs_to_many

class Employee < ActiveRecord::Base
  has_and_belongs_to_many :skills
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :employees
end

以及迁移:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM