Betterment / betterlint

MIT License
41 stars 15 forks source link

Rule for first_or_initialize without scope/where #58

Open ivangreene opened 1 week ago

ivangreene commented 1 week ago

We should flag usages of first_or_initialize that do not include a scope or where clause.

The parameters passed to first_or_initialize are not used to find the first record, so

Book.first_or_initialize(name: 'Mr. Nice')

will find any book if one exists, not just one with a matching name. This is almost never what someone wants.

The correct way to do this would be:

Book.where(name: 'Mr. Nice').first_or_initialize

N.B.: The latter will also initialize the record with name: 'Mr. Nice'. It's not immediately clear to me how other types of scopes will populate properties of the initialized record.

This could be its own rule, or an extension of UnscopedFind. It feels distinct enough of an error, with different correction concerns, that it should be its own rule