LoginSignup
4
3

More than 5 years have passed since last update.

ActiveRecord + MySQLでレコード抽出

Posted at

はじめに

本記事はドットインストールActive Record入門 (全19回)で学習した時のメモ書きである。

対象読者

ActiveRecordを勉強しようと思っている、Rubyの文法は基本的に知っている初心者

本記事の目的

ActiveRecordの一機能である、「レコード抽出機能」を理解するための自分用のアウトプット記事

実行環境

バージョン Extra
CentOS 6.9 VirtualBox経由でssh接続
VirtualBox 5.1.18
ActiveRecord 5.1.0
MySQL 5.7.18
Ruby 2.4.1 rbenvで管理
Bundler 1.14.6

各種設定/実行ファイル

Gemfile
# frozen_string_literal: true
source "https://rubygems.org"

# gem "rails"
gem "activerecord"
gem "mysql2"
gem "sinatra"
database.yml
development:
  adapter: mysql2
  database: TestApp
  host: localhost
  username: root
  password: ××××××××
  encoding: utf8
main.rb
require 'active_record'
require 'pp'
require 'mysql2'

Time.zone_default = Time.find_zone! 'Tokyo'
ActiveRecord::Base.default_timezone = :local

ActiveRecord::Base.configurations = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['development'])

class User < ActiveRecord::Base
end

# insert

User.delete_all

User.create(name: "tanaka", age: 19)
User.create(name: "takahashi", age: 25)
User.create(name: "hayashi", age: 31)
User.create(name: "mizutani", age: 28)
User.create(name: "otsuka", age: 35)

#以下をいじる

実行コマンド

bundle exec ruby main.rb

レコードの抽出

selectメソッド

抽出するフィールドを指定したい場合はselectメソッドを用いる。

selectメソッドの例
#id, name, ageの値だけ、全てのレコード分表示
pp User.select("id, name, age").all

#id, ageの値だけ、最初の3件のレコード分だけ表示
pp User.select("id, age").first(3)

ppはpretty printというツールで見やすい形で出力してくれる。

findメソッド

主キーによる検索結果を抽出したい場合はfindメソッドを用いる。

findメソッドの例
# 主キー(id)の値が3であるレコードのid, name, ageの値を抽出
pp User.select("id, name, age").find(3)

find_byメソッド

その他のフィールドによる検索結果を抽出したい場合はfind_byメソッドを用いる。
メソッドの引数に検索対象のフィールドとその値をハッシュ形式で記載する。

find_byメソッドの例
# nameがtanakaであるレコードのid, name, ageの値を抽出
# 該当するレコードがなかったらエラーを返す。
pp User.select("id, name, age").find_by!(name: "tanaka")
pp User.select("id, name, age").find_by_name! "tanaka"

メソッドの最後に!をつけると、該当レコードがない時にエラーを吐き出す。つけなかった場合はnilが返る。

whereメソッド

whereメソッドを使えば範囲指定など、より複雑な検索が可能。

whereメソッドの例
# ageの値が20から29の間にあるレコードのid, name, ageの値を抽出
pp User.select("id, name, age").where(age: 20..29)
pp User.select("id, name, age").where("age >= 20 and age < 30")#

# idが3でないレコードのid, name, ageの値を抽出
pp User.select("id, name, age").where.not(id: 3)

※注意点
条件を記述する際、変数を用いるとき、プレースホルダーを使って条件文字列に安全に値を埋め込むことが必要。

プレースホルダーを用いた例
min = 20
max = 30

#以下二つは同様の意味
#?多いと見にくいからシンボルを用いることもある
pp User.select("id, name, age").where("age >= ? and age < ?", min, max)
pp User.select("id, name, age").where("age >= :min and age < :max", {min: min, max: max})

部分一致の検索結果を抽出したい場合もプレースホルダーを用いる。

部分一致検索にプレースホルダーを用いた例
# 名前が"a"で終わるレコードのid, name, ageの値を抽出
pp User.select("id, name, age").where("name like ?", "%a")
4
3
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
3