[英]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
我有3个课程,涉及Employee,Employee_skills和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
I think your situation is a good candidate for has_many_through association 我认为您的情况非常适合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
Now simply do 现在简单地做
Skill.first.employees
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
. 首先,无需指定
class_name
或foreign_key
,因为belongs_to :employee
已经引用了类Employee
和外键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 您可以使用
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.