问题
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