我有一个 AWARD 模型 - 创建 AWARD 有两种形式。一种用于提名员工,另一种用于非员工。EMPLOYEE 表单拉出一个活跃员工列表以填充 Nominee 选择框。Non-Employee 表单只有文本字段来填充 Nominee 字段(因为我没有填充选择列表的来源)。
为了对应用程序进行虚拟验证,我想运行一个验证,禁止员工使用非员工表单(因为他们将不可避免地尝试这样做!)。每个表单上都有一个隐藏字段来设置表单是Employee还是Non: <%= f.hidden_field :employee, :value => true/false %>
因此,在 Non-Employee 表单上,如果用户键入 Employee 表中存在的 nominee_username,它应该抛出错误并将他们定向到 Employee 表单。
这是我尝试过的:
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
Award 和 Employee 模型之间存在关联,但我不知道如何在 Award 模型中调用 Employee.username 来验证 Non-Employee 表单。
class Employee < ActiveRecord::Base
has_many :awards, :foreign_key => 'nominator_id'
has_many :awards, :foreign_key => 'nominee_id'
end