2013-05-21 38 views
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 
+1

这是怎么回事? '如果Employee.where(:username => nominee_username).present?' – depa

+0

嗯,我可以把它放在奖励模型的验证方法中?将尝试它... sheesh,很容易。谢谢!!想回答,我可以接受吗? –

+0

不错,很高兴它有帮助。 :) – depa

回答

1

试试这个为您的验证方法。

def employee_using_non_employee_form 
    if Employee.where(:username => nominee_username).present? 
    errors.add(:nominator, "Please use Employee form.") 
    end 
end