繁体   English   中英

Rails验证相关字段是否具有相关字段

[英]Rails validate that related field has a related field

我有以下四个模型:

class Workgroup < ActiveRecord::Base
  has_many :empgroups
  has_many :employees, through: :empgroups
  has_many :workorders

class Empgroup < ActiveRecord::Base
  attr_accessible :employee_id, :workgroup_id
  belongs_to :employee
  belongs_to :workgroup

class Employee < ActiveRecord::Base
  has_many :empgroups
  has_many :workgroups, through: :empgroups
  has_many :workorders

class Workorder < ActiveRecord::Base        
  belongs_to :employee
  belongs_to :workgroup

创建新工作订单时,我要验证该雇员是否属于所选工作组。

如何在工作订单模型中编写验证代码?

谢谢您的帮助!

我会在工作单模型中编写一个自定义验证方法。 所以它可能看起来像这样。

class Workorder < ActiveRecord::Base        
  belongs_to :employee
  belongs_to :workgroup
  validate :check_employee_workgroup

  private
  def check_employee_workgroup
    errors.add(:employee_id, "Employee is not available in this work group") unless
    self.employee.workgroups.select(:id).where(id: [self.workgroup_id]).exists?         
  end
end

这样做的需要可能是设计问题。 也许您应该修改您的班级,使其看起来像这样:

class Workgroup < ActiveRecord::Base
    has_many :empgroups
    has_many :employees, through: :empgroups

class Empgroup < ActiveRecord::Base
    attr_accessible :employee_id, :workgroup_id
    belongs_to :employee
    belongs_to :workgroup

class Employee < ActiveRecord::Base
    has_many :empgroups
    has_many :workgroups, through: :empgroups

class Workorder < ActiveRecord::Base        
    belongs_to :empgroup

这样,您根本不需要自定义验证器。 从那里,您可以通过以下方式添加任何其他内容:必要的关系

暂无
暂无

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

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