我希望能够在数据库中创建一条记录,但是从那以后阻止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模型设置为只读?
发布评论