【问题标题】:Ruby on Rails complex search through foreign keysRuby on Rails 通过外键进行复杂搜索
【发布时间】:2017-08-25 10:54:32
【问题描述】:

您好,在我的应用程序中,我正在尝试根据技能搜索员工。我有 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

【问题讨论】:

  • 为什么需要一个技能类?
  • 当我可以通过employee_skills将许多员工分配给该技能时,我可以独立添加一项新技能
  • 这就是为什么你需要一个 has_many through 关系。试试我的答案

标签: ruby-on-rails ruby search activerecord


【解决方案1】:

我认为你的情况很适合 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

【讨论】:

  • 我收到“未找到名称‘技能’的关联。它已经定义了吗?”错误,有什么提示吗?
  • 为什么要使用这个,如果有一种本地方式 - has_and_belongs_to_many
  • 因为它是可扩展的,并且更符合 OP 的要求
【解决方案2】:

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

您可以使用has_and_belongs_to_many 关联,这适合您的需求: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

还有迁移:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多