Ruby on rails Rails更新属性安全性:使用回调或属性访问?
我有一个网站模型,需要用户验证网站的所有权 由于堆栈溢出,我能够在此处找到用户所有权验证的解决方案: 模型通过验证测试后,将有一个已验证属性设置为true 我遇到的问题是,当用户想要编辑其网站的属性时,他或她可以很容易地更改域的名称,而验证的属性保持为真,从而允许用户创建网站对象而无需验证所有权 我可以想出两种方法来解决这个问题: 1.如果网站的域名发生更改,则使用回调将验证更改为false。 2.允许域在创建新对象时可访问属性,但在更新对象时不允许访问属性 我不知道如何实际实施这两种方法。我认为你的选择#1是最好的办法。否则,您将进入尝试协调创建和更新操作的业务中——您需要这样做来处理选项2 您可以覆盖域名的setter,然后执行自定义逻辑,如下所示: 在您的模型中:Ruby on rails Rails更新属性安全性:使用回调或属性访问?,ruby-on-rails,security,activerecord,callback,Ruby On Rails,Security,Activerecord,Callback,我有一个网站模型,需要用户验证网站的所有权 由于堆栈溢出,我能够在此处找到用户所有权验证的解决方案: 模型通过验证测试后,将有一个已验证属性设置为true 我遇到的问题是,当用户想要编辑其网站的属性时,他或她可以很容易地更改域的名称,而验证的属性保持为真,从而允许用户创建网站对象而无需验证所有权 我可以想出两种方法来解决这个问题: 1.如果网站的域名发生更改,则使用回调将验证更改为false。 2.允许域在创建新对象时可访问属性,但在更新对象时不允许访问属性 我不知道如何实际实施这两种方法。我认
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
诸如此类……我认为你的选择#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
诸如此类……科迪,你的回答让我走上了正确的轨道。非常感谢 这就是我在我的案例中所追求的:
def domain=(the_domain)
if domain != the_domain
self[:domain] = the_domain
self[:verified] = false
end
end
很好。科迪,你的回答让我走上了正确的轨道。非常感谢 这就是我在我的案例中所追求的:
def domain=(the_domain)
if domain != the_domain
self[:domain] = the_domain
self[:verified] = false
end
end
它工作得很好。回调和方法绝对是解决这种情况的方法
before_update :set_domain_status
def set_domain_status
self.verified = false if self.domain_changed?
end
\u changed?可以添加到任何属性,如果值与最初从数据库加载的值不同,则返回true 回调和方法绝对是解决这种情况的方法
before_update :set_domain_status
def set_domain_status
self.verified = false if self.domain_changed?
end
\u changed?可以添加到任何属性,如果值与最初从数据库加载的值不同,则返回true 哎哟,但这弄乱了“新”动作。哎哟,但这弄乱了“新”动作。我想我会选这个。谢谢托比!我想我会选这个。谢谢托比!