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:
I assumed that you have association named
userand that your user object responds toadmin?method.