如何在 Rails 中将数据库字段设置为只读?
我有一个包含某个字段的数据库表,一旦将其插入数据库,就不可能更新该字段。如何告诉我的模型它不应允许更新某个字段?
I have a database table with a certain field which should be impossible to update once it has been inserted to the database. How do I tell my model that it shouldn't allow updating of a certain field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想使用
attr_readonly
< /a>:You want to use
attr_readonly
:这是我对类似问题的相关解决方案 - 我们希望用户能够自行设置字段,我们在创建记录时不需要它们,但我们不希望它们在设置后被更改。
但令我惊讶的是,
update_attribute
仍然有效,它绕过了验证。没什么大不了的,因为记录的更新在实践中是大量分配的 - 但我在测试中指出了这一点以使其清楚。这是一些测试。Here's my related solution to a similar problem - we have fields that we want a user to be able to set themselves, we don't require them on creation of the record, but we do NOT want to them be changed once they are set.
The thing that surprised me, though, was that
update_attribute
still works, it bypasses the validations. Not a huge deal, since updates to the record are mass assigned in practice - but I called that out in the tests to make it clear. Here's some tests for it.