LoginSignup
4
4

More than 5 years have passed since last update.

rails3.2 と 4.1 での ActiveRecord select の違い

Posted at

rails4.1 では ActiveRecord select で id を指定していないにもかかわらず、オブジェクトに id: nil を含んでしまうようです。
to_json する際に注意が必要そう。

desc users;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| nickname   | varchar(255) | YES  |     | NULL    |                |
| birthday   | datetime     | YES  |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

rails3.2

> User.select([:nickname, :birthday])
=> [#<User nickname: "hoge", birthday: "2014-08-18 06:08:35">, #<User nickname: "hoge2", birthday: "2014-08-18 06:08:39">, #<User nickname: "hoge3", birthday: "2014-08-18 06:08:42">]
> User.select([:nickname, :birthday]).to_json
=> "[{\"birthday\":\"2014-08-18T06:08:35Z\",\"nickname\":\"hoge\"},{\"birthday\":\"2014-08-18T06:08:39Z\",\"nickname\":\"hoge2\"},{\"birthday\":\"2014-08-18T06:08:42Z\",\"nickname\":\"hoge3\"}]"

rails4.1

> User.select([:nickname, :birthday])
=> #<ActiveRecord::Relation [#<User id: nil, nickname: "hoge", birthday: "2014-04-30 03:01:24">, #<User id: nil, nickname: "hoge2", birthday: "2014-03-31 03:01:31">, #<User id: nil, nickname: "hoge3", birthday: "2013-12-08 03:01:40">]>
> User.select([:nickname, :birthday]).to_json
=> "[{\"nickname\":\"hoge\",\"birthday\":\"2014-04-30T03:01:24.000Z\",\"id\":null},{\"nickname\":\"hoge2\",\"birthday\":\"2014-03-31T03:01:31.000Z\",\"id\":null},{\"nickname\":\"hoge3\",\"birthday\":\"2013-12-08T03:01:40.000Z\",\"id\":null}]"
4
4
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
4
4