有没有一种简单的方法可以将Rails ActiveRecord模型设置为只读?

编程入门 行业动态 更新时间:2024-10-04 19:32:40
本文介绍了有没有一种简单的方法可以将Rails ActiveRecord模型设置为只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够在数据库中创建一条记录,但是从那以后阻止Rails进行更改。我知道在数据库级别仍然可以进行更改。

I want to be able to create a record in the DB but then prevent Rails from making changes from that point on. I understand changes will still be possible at the DB level.

我相信attr_readonly可以满足我在属性级别上的要求,但是我不想手动指定字段...我宁愿有更多的白名单方法。

I believe attr_readonly does what I want on an attribute level, but I don't want to have to manually specify fields... I would rather have more of a white-list approach.

此外,我知道关联有一个:read_only选项,但我不想将对象的只读性限制为是否通过关联获取。

Also, I know there is a :read_only option for associations, but I don't want to limit the "readonlyness" of the object to if it was fetched via an association or not.

最后,我希望仍然能够销毁记录,因此:depend =>:destroy在关联中起作用。

Finally, I want to be able to still destroy a record so stuff like :dependent => :destroy works in the associations.

因此,总结一下:1)允许创建记录,2)允许删除记录,和3)防止更改已保留的记录。

So, to summarize: 1) allow the creation of records, 2) allow the deletion of records, and 3) prevent changing records that have been persisted.

推荐答案

查看 ActiveRecord :: Persistence ,一切最终都在幕后调用 create_or_update 。

def create_or_update raise ReadOnlyRecord if readonly? result = new_record? ? create : update result != false end

所以!只是:

def readonly? !new_record? end

更多推荐

有没有一种简单的方法可以将Rails ActiveRecord模型设置为只读?

本文发布于:2023-11-29 02:08:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644870.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   模型   简单   方法   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!