[英]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_name
或foreign_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.