如何在较新的Rails上用readonly替换find? [英] How to replace find by readonly on newer Rails?

查看:72
本文介绍了如何在较新的Rails上用readonly替换find?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有以下旧代码:

I had this legacy code in my project:

Model.find(id, :readonly => false)

显然,它是按id搜索的,并且仅搜索非只读对象。但是readonly不是Model的属性,应该检查实际的ActiveRecord属性,该属性定义该实例是否为只读实例。我不知道这是否是这段代码的实际作用,也许:readonly => false在那里没有用。但是我得到了预期的警告:

Apparently, it searched by id and only the objects that were not readonly. But readonly is not an attribute of the Model, this should be checking the actual ActiveRecord property that defines whether that instance is a read only instance or not. I don't know if that is what this code actually does, maybe that :readonly => false is useless there. But I get the expected warning:

DEPRECATION WARNING: Passing options to #find is deprecated. Please build a scope and then call #find on it.

我不能用where替换它,因为我无法检查其中的只读性SQL,因为它不是SQL属性。

And I can't replace it with a where, because I can't check for readonlyness in the SQL, since it is not a SQL attribute.

该错误实际上明确指出即使在范围内,我仍然可以使用find。但是我做了一个范围,像这样:

The error actually explicitly states that I can still use find, if within a scope. But I made a scope, like so:

scope :by_id_not_readonly, ->(id) { find(id, :readonly => false) }

但是会抛出相同的警告,但是在范围声明行中模型而不是控制器...

But the same warning is thrown, but in the scope declaration line in the model instead of the controller...


我做了其他一些测试:


I made some other tests:

将其替换加上where('id =?AND readonly = false',id)实际上会产生错误,但例外情况是-readonly不适用于该模型。

Replacing it with where('id = ? AND readonly = false', id) actually gives an error, as excepted - readonly is not a properly of the model.

运行代码没有只读位会破坏测试,因为它会返回只读记录,并且代码稍后会尝试更新它们,从而产生错误。

Running the code without the readonly bit breaks the tests, because it returns the readonly records and the code later tries to update them, giving an error.

向查找哈希添加错误的选项,例如find(id,:readonly => false,:ldisfs32j9fmdf90sdfds => false)给出未知的密钥错误,除外。

Adding an incorrect option to the find hash, e.g. find(id, :readonly => false, :ldisfs32j9fmdf90sdfds => false) gives an unknown key error, as excepted.


因此,此:readonly位至关重要,但我无法用简单的位置代替它。


So, this :readonly bit is crucial, but I can't replace it with a simple where. How can I do it in the newer versions of rails?

推荐答案

尝试一下:

 Model.readonly(false).find(id)

它不在哪里使用

这篇关于如何在较新的Rails上用readonly替换find?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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