LoginSignup
19
32

More than 5 years have passed since last update.

Ruby on Railsを使っての基本的なデータ取得を学ぶ

Posted at

RubyOnRailsの基本的なデータ取得方法をまとめます。

環境

  • CentOS6.5
  • Rails 5.1.4
  • MySQL 5.7

RailsでMySQLのテーブル作成で作成したテーブルを使います。

全件取得

users = User.all

条件付き

id = 1

users = User.where("id = ?", 1)

プライマリキーを条件に使う場合はこのようにも書ける

users = User.find(1)

上の場合は何件返ってくるかわからない。下の場合はプライマリキー用の取得方法なので最大1件返ってくる。

id > 5 かつ id < 10

users = User.where("id > ? and id < ?", 5, 10)

指定したカラムのみ取得

users = User.select('id, age')

Group by

users = User.select('age, count(*) as count').group('age')

Group by having

users = User.select('age, count(*) as count').group('age').having('count > ?', 50)

Limit(取得件数上限)

users = User.select('id, age').limit(10)

Order by

ASC(昇順)

users = User.limit(10).order('id')

DESC(降順)

users = User.limit(10).order('id DESC')
19
32
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
19
32