How to replace find by readonly on newer Rails?

你。 提交于 2019-12-06 07:49:55

问题


I had this legacy code in my project:

Model.find(id, :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.

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.

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:

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.

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


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?


回答1:


Try this:

 Model.readonly(false).find(id)

it's not using where



来源:https://stackoverflow.com/questions/23542623/how-to-replace-find-by-readonly-on-newer-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!