Skip to content

Commit

Permalink
Fix the behavior when passing nil to exists?
Browse files Browse the repository at this point in the history
Currently, the behavior when passing `nil` to `exists?` doesn't match
with Rails's behavior. Rails always returns `false`, but ActiveHash not.
https://github.com/rails/rails/blob/5a0b2fa5a3be6ffd49fa7f1c3544c1da403c9cb5/activerecord/lib/active_record/relation/finder_methods.rb#L367

This PR changes the behavior to match with Rails's.
  • Loading branch information
y-yagi committed Aug 27, 2024
1 parent 627dc17 commit 2c36e6a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/active_hash/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,12 @@ def data=(array_of_hashes)
end
end

def exists?(args = nil)
def exists?(args = :none)
if args.respond_to?(:id)
record_index[args.id.to_s].present?
elsif args == false
elsif !args
false
elsif args.nil?
elsif args == :none
all.present?
elsif args.is_a?(Hash)
all.where(args).present?
Expand Down
6 changes: 6 additions & 0 deletions spec/active_hash/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,12 @@ def continent
end
end

context "when nil is passed" do
it "return nil" do
expect(Country.exists?(nil)).to be_falsy
end
end

describe "with matches" do
context 'for a record argument' do
it "return true" do
Expand Down

0 comments on commit 2c36e6a

Please sign in to comment.