0

How would I make this work? I want to validate an award nomination based on criteria from a different model.

      class Award < ActiveRecord::Base

  belongs_to :manager, :class_name => 'Manager', :foreign_key => 'manager_username'



  def cant_be_manager
     if nominee_username == Manager.username   
       errors.add(:nominee, "is a manager and cannot be nominated.")
     end
  end

end
4

2 回答 2

2

Try this:

class Award < ActiveRecord::Base

  belongs_to :manager, :class_name => 'Employee', :foreign_key => 'manager_username'

  validate :cant_be_manager  # <----- added this line

  def cant_be_manager
     if nominee_username == manager.username    # <----- lower case m
       errors.add(:nominee, "is a manager and cannot be nominated.")
     end
  end

end

But (just guessing here what your model looks like) I'm wondering if that second modified line shouldn't be:

if nominee_username == manager_username    

The belongs_to line indicates that you have a manager_username field in your awards table, but it would be more common in Rails for this to be a manager_id field, with the belongs_to line looking like this:

belongs_to :manager, :class_name => 'Employee', :foreign_key => 'manager_id'

If that is indeed what you have, your code should look like this:

class Award < ActiveRecord::Base

  belongs_to :manager, :class_name => 'Employee', :foreign_key => 'manager_id'  # <----- changed

  validate :cant_be_manager  # <----- added this line

  def cant_be_manager
     if nominee_id == manager_id    # <----- changed
       errors.add(:nominee, "is a manager and cannot be nominated.")
     end
  end

end

This assumes that you are trying to prevent an employee from nominating his own manager, but it's okay for the employee to nominate other managers, or for managers to nominate other managers. If instead you want to prevent any managers at all from being nominated by anyone, let me know how you know if an Employee is a manager (probably an attribute or method on your Employee model) and I will update the answer.

于 2013-05-20T20:19:42.360 回答
0

Maybe smth. like this?

class Award < ActiveRecord::Base
  validate :cant_be_manager

  def cant_be_manager
  .....
end

See this question too: Rails custom validation

于 2013-05-20T20:15:52.347 回答