Rails 3.2 - 基于其他模型标准在模型中验证

时间:2013-05-21 15:57:19

标签: ruby-on-rails-3

我有一个AWARD模型 - 创建一个AWARD有两种形式。一个是提名员工,另一个是非员工。 EMPLOYEE表单提取了一个活跃员工列表以填充Nominee选择框。 Non-Employee表单只有填充Nominee字段的文本字段(因为我没有填充选择列表的来源)。

为了对应用程序进行虚拟证明,我想运行一个不允许员工使用非员工表单的验证(因为他们不可避免地会尝试这样做!)。每个表单上都有一个隐藏字段,用于设置表单是Employee还是Non:<%= f.hidden_field :employee, :value => true/false %>

因此,在非员工表单上,如果用户键入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来验证非Employee表单。

  class Employee < ActiveRecord::Base
      has_many :awards, :foreign_key => 'nominator_id'
      has_many :awards, :foreign_key => 'nominee_id'
  end

1 个答案:

答案 0 :(得分:1)

尝试使用此验证方法。

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