Skip to content

find_by with nil value will return an object with an empty string #293

@tomohung

Description

@tomohung

Environment

  • Ruby 3.0.6
  • Rails 6.1.5
  • ActiveHash 3.2.1

Problem

Running the script from the console

class Vehicle < ActiveHash::Base
  self.data = [
    {
      id: 1,
      name: "Wagon",
      code: "1"
    },
    {
      id: 2,
      name: "rocket",
      code: ""
    }
  ]
end

Vehicle.find_by(code: "")&.id
# expected: 2, return: 2

Vehicle.find_by(code: nil)&.id
# expected: nil, return: 2

as the second example should return nil but not the record (id: 2)

Potential solution

It looks like we introduced from
https://github.com/active-hash/active_hash/pull/268/files#diff-3d428d32c562c13eaacc6f541b1c94625f24cf74f1c42a9f7ee06999647773dbR42
that didn't consider nil case.

This could solve the issue

module ActiveHash
  class Relation
    class Condition
      def normalize(value)
        return value if value.nil?

        value.respond_to?(:to_s) ? value.to_s : value
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions