Anisha
Anisha

Reputation: 19

Unexpected behaviour depicted by find_by id in rails

I am facing a very weird problem, when a string containing number and alphabets is provided to find_by it internally runs to_i on string(as per observation) provided and return the object. I was expecting that it should return nil in that case. Please help me out in this.

Shop.find_by(id: '22456a12m3')
  Shop Load (0.6ms)  SELECT  "shops".* FROM "shops" WHERE "shops"."cancelled_at" IS NULL AND "shops"."id" = $1 LIMIT $2  [["id", 22456], ["LIMIT", 1]]

Upvotes: 0

Views: 52

Answers (1)

bhugo313
bhugo313

Reputation: 451

Based on the API documentation, they call to_i for integer id field.

If the primary key is an integer, find by id coerces its arguments by using to_i.

Upvotes: 3

Related Questions