Can’t this be mitigated by using the bang-variant? i.e. `find_by_id!` ?
On Mon, Nov 10, 2014 at 8:03 AM, Eugene Gilburg <[email protected]>
wrote:
> Current behavior:
> User.find_by_id(nil)
> User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" IS
> NULL LIMIT 1
> User.find_by_id("")
> User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 0
> LIMIT 1
> I realize it's hard to always be able to tell whether given parameter can
> exist or not, but above cases seem like pretty obvious, and also the most
> common cases (e.g. accepting blank param from request), or chaining queries
> where previous query returned nil.
> Interestingly enough, User.find(nil) raises right away without queries, but
> not User.find_by_id(nil).
> I noticed my code often ends up like:
> User.find_by_id(id) if id.present?
> This seems like unnecessary cruft that the app should in many cases know on
> its own, at least in following cases:
> - Looking up nil on column which has NOT NULL constraint.
> - Looking up blank string on integer db field (common when passing
> request param to query). This will be casted to 0, but unlike explicit
> find_by_id(0), which theoretically could exist in db via manual insertion,
> I think it's safe to assume that anyone passing blank string to find_by_id
> and friends should expect it to be treated as nil and not 0.
> Could Rails check the db schema and know whether nil/blank values are
> possible in db? If not, it could short-circuit or use NullScope to avoid
> making unnecessary query.
> Thanks!
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/rubyonrails-core.
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.