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