0
我有一個AWARD模型 - 有兩種形式可以創建AWARD。一個是提名僱員,另一個是非員工。 EMPLOYEE表格拉出一系列活躍的員工填充提名人選擇框。 Non-Employee表單只有文本字段才能填充提名字段(因爲我沒有來源來填充選擇列表)。Rails 3.2 - 基於其他模型標準進行驗證
要僞造應用程序,我想運行驗證,不允許員工使用非員工表單(因爲他們將不可避免地嘗試這麼做!)。每個表單上都有一個隱藏字段來設置表單是Employee還是Non:<%= f.hidden_field :employee, :value => true/false %>
因此,在Non-Employee表單上,如果用戶鍵入Employee表中存在的nominee_username,它應該拋出一個錯誤並將其引導至員工表單。
這是我已經嘗試:
class Award < ActiveRecord::Base
belongs_to :nominator, :class_name => 'Employee', :foreign_key => 'nominator_id'
belongs_to :nominee, :class_name => 'Employee', :foreign_key => 'nominee_id'
validate :employee_using_non_employee_form,
:on => :create, :unless => :employee_nomination?
def employee_nomination?
self.employee == true
end
def employee_using_non_employee_form
if nominee_username == employee.username ## -- this is where I'm getting errors. I get "undefined local variable or method employee for #<Award:.."
## I've also tried Employee.username, but get "undefined method username for #<Class..."
## Same error when I try nominee.username
errors.add(:nominator, "Please use Employee form.")
end
end
end
還有就是獎和員工模型之間的關聯,但我不知道如何調用Employee.username獎模型中,以驗證非 - 員工形式。
class Employee < ActiveRecord::Base
has_many :awards, :foreign_key => 'nominator_id'
has_many :awards, :foreign_key => 'nominee_id'
end
這是怎麼回事? '如果Employee.where(:username => nominee_username).present?' – depa
嗯,我可以把它放在獎勵模型的驗證方法中?將嘗試它... sheesh,很容易。謝謝!!想回答,我可以接受嗎? –
不錯,很高興它有幫助。 :) – depa