Rails 3.2 - Validate in Model Based on Other Model Criteria -


i have award model - there 2 forms create award. 1 nominating employees, other non-employees. employee form pulls list of active employees populate nominee selection box. non-employee form has text fields populate nominee field (because have no source populate selection list).

to dummy-proof app, want run validation disallows employees using non-employee form (because inevitably try so!). there hidden field on each form set whether form employee or non: <%= f.hidden_field :employee, :value => true/false %>

so, on non-employee form, if user types in nominee_username exists in employee table, should throw error , direct them employee form.

here's i've attempted:

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  ##  --  i'm getting errors.  "undefined local variable or method employee #<award:.."                                               ## i've tried employee.username, "undefined method username #<class..."                                               ## same error when try nominee.username       errors.add(:nominator, "please use employee form.")     end   end  end 

there association between award , employee models, don't know how call employee.username within award model validate non-employee form.

  class employee < activerecord::base       has_many :awards, :foreign_key => 'nominator_id'       has_many :awards, :foreign_key => 'nominee_id'   end 

try validation method.

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

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -