Validation Based Upon Associated Record
I have two models: User and Lesson. I only want lessons to be assigned to users that are admins.
What is the best way to ensure this? I am currently attempting to create a custom validator like so:
class BelongsToAdminValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value.admin?
object.errors[attribute] << (options[:message] || "must belong to an admin")
end
end
end
But this leads to Rspec saying:
undefined method `admin?开发者_高级运维' for nil:NilClass
Which makes sense.
Is a custom validator the best way to do this? Or should I be checking if the to-be-assigned user is an admin in a controller?
I think that the easiest way of doing it is:
# Lesson model
validate :allow_only_admins
private
def allow_only_admins
errors.add(:user, "must be admin user!") if (user.blank? || !user.admin?)
end
I assumed that you have association named user
and that your user object responds to admin?
method.
精彩评论