-
Notifications
You must be signed in to change notification settings - Fork 179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Accessing belongs_to association without a key creates a useless query #302
Comments
So the request is to throw an error if the model does not have a Wonder if this will cause an issue if a model defines associations before fields. |
No, it is that when the association foreign key is nil then just do a noop instead of calling Hope that makes sense 🙏 |
Ugh. Your test script is pretty clear here. Sorry. (see the last query below) I do like how rails avoids this query. I am a little concerned that people will want to query for a nil id. Yes, Rails only supports models with a unique present id, but since when have people followed strict Rails?
|
Sadly I agree 😭 My next thought was an opt-in option on the association method to enable this behaviour. Seems clunky and it would be hard naming it but then at least it doesn't break existing usage. |
Environment
Problem
When accessing a
belongs_to
association, if the related id is missing then a query forid IS NULL
is made. This is different from the standard ActiveRecord behaviour and I think in 99% of cases a redundant query. Seems to be caused by the internal use offind_by_id
with a blank argument: https://github.com/active-hash/active_hash/blob/master/lib/associations/associations.rb#L177You can reproduce and observe with this script:
Potential Solution
Don't bother querying if the key is NULL, if there is some weird edge case where you would want this then perhaps the behaviour could be enabled with a config option or optional argument when defining the association.
The text was updated successfully, but these errors were encountered: