基于相关记录的验证
我有两个模型:用户和课程。我只想将课程分配给管理员用户。
确保这一点的最佳方法是什么?我目前正在尝试创建一个自定义验证器,如下所示:
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
但这导致 Rspec 说:
undefined method `admin?' for nil:NilClass
这是有道理的。
自定义验证器是执行此操作的最佳方法吗?或者我应该检查要分配的用户是否是控制器中的管理员?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为最简单的方法是:
我假设您有名为
user
的关联,并且您的用户对象响应admin?
方法。I think that the easiest way of doing it is:
I assumed that you have association named
user
and that your user object responds toadmin?
method.