LoginSignup
7
10

More than 5 years have passed since last update.

Active Recordの色々なメソッドの返り値

Posted at

Active Recordでよく使われるfindwhereなどのメソッドの返り値について調べたらこうなった.

Commentの部分は, Commentという名前のモデルを意味しています. 検索条件に該当したレコードのインスタンスが返ってきていることを意味します.
image.png

ちなみに以下のようにして調べた.

Comment.all.class
=> Comment::ActiveRecord_Relation

Comment.find(10401).class
=> Comment(id: integer, body: text, commentable_id: integer, user_id: integer, likes_count: integer, created_at: datetime, updated_at: datetime, commentable_type: string)

Comment.find(10401, 10402).class
=> Array

Comment.find_by_id(10401).class
=> Comment(id: integer, body: text, commentable_id: integer, user_id: integer, likes_count: integer, created_at: datetime, updated_at: datetime, commentable_type: string)

Comment.find_by({id:10401}).class
=> Comment(id: integer, body: text, commentable_id: integer, user_id: integer, likes_count: integer, created_at: datetime, updated_at: datetime, commentable_type: string)

Comment.where({id:10401}).class
=> Comment::ActiveRecord_Relation

Comment.all.page(10).class
=> Comment::ActiveRecord_Relation

Comment.all.first.class
=> Comment(id: integer, body: text, commentable_id: integer, user_id: integer, likes_count: integer, created_at: datetime, updated_at: datetime, commentable_type: string)

Comment.all.last.class
=> Comment(id: integer, body: text, commentable_id: integer, user_id: integer, likes_count: integer, created_at: datetime, updated_at: datetime, commentable_type: string)

Comment.includes(:user).class
=> Comment::ActiveRecord_Relation

Comment.order('created_at DESC').class
=> Comment::ActiveRecord_Relation

・ ActiveRecord_Relation ってなんぞ

ActiveRecord_Relationが返ってきた時点ではまだSQLは発行されていない. 描画に必要になったときに初めてSQLが発行される仕組み成っている. また, メソッドチェーンでwhereorderなどを続けて書くことができる, という便利な機能.

7
10
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
7
10