有没有一种简单的方法可以将Rails ActiveRecord模型设置为只读? [英] Is there an easy way to make a Rails ActiveRecord model read-only?

查看:57
本文介绍了有没有一种简单的方法可以将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模型设置为只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆