LoginSignup
65
78

More than 5 years have passed since last update.

Rails Active Recordのまとめ

Last updated at Posted at 2015-06-08

Active Recordとは?

データベースからデータを読み出すアプローチ。(Wikipediaより)
Rails4対応。

基本編

Class.create

レコードを作成し、データベースへの保存。

article = Article.create(title: 'hoge', content: 'hogehoge')

Class.new

オブジェクトのインスタンス化。

article = Article.new

Class.save

インスタンスのデータベースへの保存。

article = Article.new
article.title = 'hoge'
article.content = 'hogehgoe'
article.save

create = new + save

Class.build

new ≒ buildではあるが、buildは自動参照キーを自動でセットしてくれる。

@article = Article.find(1)
@comments = @article.comments.build

findについては後述。

article_idをセットしてくれる。

Class.all

レコード全件取得。

article = Article.all

Class.first

レコードの最初の1件取得。

article = Article.first

Class.find

idで1件取得。

article = Article.find(1)

Class.find_by

特定フィールドで最初の1件取得。

article = Article.find_by(title: 'hoge')

Class.where().first

特定フィールドで最初の1件取得。
find_byと同じ役割。

article = Article.where(title: 'hoge').first

Class.where

特定フィールドで全件取得。

article = Article.where(title: 'hoge')

Class.update

レコードの更新。

article = Article.find(1)
article.update(title: 'hogehoge')

Class.destroy

レコードの削除。

article = Article.find(1)
article.destroy

便利メソッド

Class.where().first_or_initialize

要素があれば最初の要素を取得。なければ、newインスタンスの生成。
ただし、saveを使用しないとsaveされない。

Article.where(title: 'hoge').first_or_initialize

ex.titleで検証してcontentも含めてsaveする。

article = Article.where(title: 'hoge').first_or_initialize
article.content = 'hogehoge'
article.save

Class.where().first_or_create

first_or_initializeのsaveまでやってくれる版。

article = Article.where(title: 'hoge').first_or_create

Class.ids

idの配列を作る。

article = Article.ids

Class.pluck()

特定フィールドで配列を作る。

article = Article.pluck(:title)

終わりに

便利なメソッドが見つかり次第、追加していく予定です。

参考
Active Record の基礎http://railsguides.jp/active_record_basics.html

65
78
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
65
78