【Rails】limitメソッドで取得するデータの件数を指定する方法

limitメソッドの使い方

取得したいレコードの件数を指定したい場合は、limitメソッドを使います。

例えば、10個あるレコードから5個取り出したい時は、以下のように記述します。

モデル名.limit(5)

参考例

[前提]name,age,genderの3つのカラムをもつUserテーブル

・Userテーブルから、5つのレコードを取得する場合。

[1] pry(main)> User.limit(5)
  User Load (2.2ms)  SELECT `users`.* FROM `users` LIMIT 5
=> [#<User:0x0000000113269e68 id: 1, name: "田中", age: 23, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.806163000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.806163000 UTC +00:00>,
 #<User:0x0000000113269cd8 id: 2, name: "田中", age: 21, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00>,
 #<User:0x0000000113269b70 id: 3, name: "佐藤", age: 23, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.812049000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.812049000 UTC +00:00>,
 #<User:0x0000000113269a08 id: 4, name: "佐藤", age: 24, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.814096000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.814096000 UTC +00:00>,
 #<User:0x00000001132698c8 id: 5, name: "山田", age: 22, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00>]

Userテーブルから、orderメソッドでageカラムを降順に並び替えた上で、5つのレコードを取得する場合

[2] pry(main)> User.order('age').limit(5)
  User Load (22.1ms)  SELECT `users`.* FROM `users` ORDER BY age LIMIT 5
=> [#<User:0x00000001130923b0 id: 2, name: "田中", age: 21, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00>,
 #<User:0x00000001130bb580 id: 8, name: "加藤", age: 21, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.823235000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.823235000 UTC +00:00>,
 #<User:0x00000001130bb468 id: 11, name: "藤原", age: 21, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.828604000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.828604000 UTC +00:00>,
 #<User:0x00000001130bb300 id: 5, name: "山田", age: 22, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00>,
 #<User:0x00000001130bb210 id: 1, name: "田中", age: 23, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.806163000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.806163000 UTC +00:00>]
タイトルとURLをコピーしました