Home > Net >  ActiveRecord inconsistent behavior?
ActiveRecord inconsistent behavior?

Time:04-07

I have a Rails 7 application, with a user model. I am experimenting with the console.

I have a User model, with only one record in it:

{"id":"1, "email":"[email protected]"}

I started a console session:

rails c

Then I did:

user = User.find(1)

Which gave me:

irb(main):009:0> user = User.find(1)
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> #<User id: 1, email: "[email protected]", created_at: "2022-04-04 12:32:14.000515000  0000", updated_at: "2022-04-04 12:32:14.000515000  0000">

irb(main):010:0>

Then I did:

irb(main):010:0> user.nil?

And the response was:

=> false

Then I did:

user = User.find(2)

And the result was:

  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1

/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/activerecord-7.0.2.2/lib/active_record/core.rb:284:in `find': Couldn't find User with 'id'=2 (ActiveRecord::RecordNotFound)

Then I did:

user.nil?

And I was expecting the result to be true, instead I got:

=> false

Why?

CodePudding user response:

When you said:

user = User.find(2)

find raised an ActiveRecord::RecordNotFound exception so the assignment never happens and user doesn't change. If you look at user here you'll see that it is what User.find(1) gave you.

  • Related