ruby on rails - Validation Based Upon Associated Record -
i have 2 models: user , lesson. want lessons assigned users admins.
what best way ensure this? attempting create custom validator so:
class belongstoadminvalidator < activemodel::eachvalidator def validate_each(object, attribute, value) unless value.admin? object.errors[attribute] << (options[:message] || "must belong admin") end end end
but leads rspec saying:
undefined method `admin?' nil:nilclass
which makes sense.
is custom validator best way this? or should checking if to-be-assigned user admin in controller?
i think easiest way of doing is:
# lesson model validate :allow_only_admins private def allow_only_admins errors.add(:user, "must admin user!") if (user.blank? || !user.admin?) end
i assumed have association named user
, user object responds admin?
method.
Comments
Post a Comment