ActiveRecord の size メソッドの落とし穴

size メソッドは、count メソッドと length メソッドのいいとこどりのメソッドです。

  • 既にデータがロードされていれば、それを使う
  • sql 発行されない
  • データがロードされていなければ、select count(*) from ... を発行する

なので多用していたのですが、このたび一つ失敗しました。

例えば User モデルに紐付いた Invitation モデルがあるとします。

invitation = current_user.invitations.build
current_user.invitations.size    # => 1
current_user.invitations.length # => 1
current_user.invitations.count  # => 0

関連の build メソッドで Invitation を増やすと、DB に入っていない状態にもかかわらず一つ増えた扱いになるのです。length も一緒。なので DB に入っている関連の数を取得したい場合は、count を使うのが良いですね。

追記

build で関連を増やすとその後の状態に影響するの、Rails 4.0 からっぽいです

emacsclient を homebrew でインストールしたものに変更

brew edit emacs

としたときにエラー。

emacsclient: can't find socket; have you started the server?
To start the server in Emacs, type "M-x server-start".
emacsclient: No socket or alternate editor.  Please use:

    --socket-name
    --server-file      (or environment variable EMACS_SERVER_FILE)
    --alternate-editor (or environment variable ALTERNATE_EDITOR)

emacsclient と emacs のバージョンが合っていないのが原因。

emacs は brew で install 済み。

brew ln --overwrite emacs 

で emacsclient や emacs コマンドを /usr/local/bin にコピーして解決。

mac mini の HDD を SSD に換装した

家の mac mini、外で使う macbook pro や air より数段遅くて使う気にならなかったのだけれど、どうやらSSDに換装できるらしいので購入して換装した。

アップグレードキットと銘打っているので、これだけで換装できるのかとおもいきや、そうではなくてトルクスドライバーがもう一つ必要だった。たまたま持っていたので助かったけど、これはどこかに書いておいて欲しかったな…。

とりあえず換装した結果、普通に使う分には air や pro と遜色ない速さになったので満足。