我有一个网站模型,需要用户验证网站的所有权。
多亏了堆栈溢出,我能够在这里找到用户所有权验证的解决方案:Validate website ownership in rails
在模型通过验证测试之后,有一个已验证的属性被设置为true。
我遇到的问题是,当用户想要编辑他或她的网站的属性时,他或她可以很容易地更改域名,而验证的属性仍然为真,从而允许用户在不验证所有权的情况下创建网站对象。
我可以想到两种解决方案: 1.有一个回调,如果网站的域名发生变化,则会将验证更改为false。2.在创建新对象时允许域名使用attr_accessible,但在更新时不允许。
我对如何在实践中实现这两种方法感到困惑。
发布于 2010-01-28 11:56:47
回调和Active Record Dirty方法绝对是解决这种情况的好方法。
before_update :set_domain_status
def set_domain_status
self.verified = false if self.domain_changed?
end_changed?可以添加到任何属性中,如果值与最初从数据库加载的值不同,则返回true。
发布于 2010-01-28 09:24:25
我认为你的Option#1是最好的路线。否则,您将进入尝试协调、创建和更新操作的业务-您需要这样做才能处理选项#2。
您可以覆盖域名的setter,然后执行自定义逻辑,如下所示:
在您的模型中:
def domain=(the_domain)
raise ValidOwnerRequired if verified? && domain != the_domain
# if we got here then the this record is new and this is a creation attempt
@require_domain_verification = true
# do other stuff here..
end
def require_domain_verification?
@require_domain_verification == true
end然后有一个观察者来观察这个模型:
def after_save(record)
if record.require_domain_verification?
SomeMailer.deliver_domain_verification(record)
end
end诸如此类的事情。
发布于 2010-01-28 09:49:46
科迪,你的回答让我找到了正确的方向。非常感谢!
这就是我在我的例子中想要的:
def domain=(the_domain)
if domain != the_domain
self[:domain] = the_domain
self[:verified] = false
end
end它工作得很好。
https://stackoverflow.com/questions/2151580
复制相似问题