【问题标题】:Rails 3.2 - Validate in Model Based on Other Model CriteriaRails 3.2 - 基于其他模型标准的模型验证
【发布时间】:2013-05-21 15:57:18
【问题描述】:

我有一个 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

【问题讨论】:

  • 这个怎么样? if Employee.where(:username =&gt; nominee_username).present?
  • 嗯,我可以把它放在奖励模型的验证方法中吗?会试试的……哎呀,太容易了。谢谢!!要回答以便我接受吗?
  • 很好,很高兴它有帮助。 :)

标签: ruby-on-rails-3


【解决方案1】:

试试这个作为你的验证方法。

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

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多