Rails 3.2 - 基于另一个模型在模型中验证

时间:2013-07-01 16:03:13

标签: ruby-on-rails-3

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

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

因此,在非员工表格中,如果用户输入他自己的nominee_username,则应该抛出一个错误,表示他无法提名自己。

我有一个验证,但即使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 :cant_nominate_self_non_employee_form,
                                :on => :create, :unless => :employee_nomination?


  def employee_nomination?
   self.employee == true
  end

##### the validation below is not working properly - it throws error every time ####
##### only if Employee.username is equal to award.nominee_username, it should error ####

def cant_nominate_self_non_employee_form
  if Employee.where(:username => nominee_username)
    errors.add(:nominator, "can't nominate yourself")
  end
end

end

奖励和员工模型之间存在关联:

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

0 个答案:

没有答案
相关问题