11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby (MRI) における 4、それは

Posted at

ときどき

blog.author_id #=> 4

あれ、author_id 4 なんて存在しないのになんで 4 が入ってるんだろ、というような挙動に出くわすことがあります。

これは、

blog.author_id = author.id

のようなコードがあり、validation が書かれていないと、Ruby (MRI 1.8)の場合

[1] pry(main)> RUBY_VERSION
=> "1.8.7"
[2] pry(main)> nil.id
(pry):2: warning: Object#id will be deprecated; use Object#object_id
=> 4

という挙動になってしまいます。そのため author が nil なら 4 が代入されてしまうわけです(Rails なら whiny_nils を設定することで防げます)

Ruby 1.8 を新規開発で使うことはいまさら無いとは思いますが、一時期 1.8 を使っていた場合、場合により 4 が入っていることもあるので、みなさん気をつけましょう。

Ruby (現状の MRI) における 4。それは nil の object_id の値でした。

ちなみに、facebook における id = 4 はマーク・ザッカーバーグです!

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?