私は AWARD モデルを持っています - AWARD を作成するには 2 つの形式があります。1 つは EMPLOYEES の指名用で、もう 1 つは非従業員用です。EMPLOYEE フォームは、アクティブな従業員のリストを取得して、候補者選択ボックスに入力します。Non-Employee フォームには、Nominee フィールドを入力するためのテキスト フィールドしかありません (選択リストを入力するソースがないため)。
アプリをダミーで証明するために、従業員が非従業員フォームを使用することを禁止する検証を実行したいと考えています (従業員は必然的にそうしようとするためです!)。各フォームには、フォームが従業員か非従業員かを設定する隠しフィールドがあります。 <%= f.hidden_field :employee, :value => true/false %>
したがって、非従業員フォームで、ユーザーが従業員テーブルに存在する 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
Award モデルと Employee モデルの間には関連付けがありますが、Award モデル内で Employee.username を呼び出して非従業員フォームを検証する方法がわかりません。
class Employee < ActiveRecord::Base
has_many :awards, :foreign_key => 'nominator_id'
has_many :awards, :foreign_key => 'nominee_id'
end