Rails: "has_many", "blongs_to"でリレーショナルなテーブル関係を設定する
UserとPostのような1つに対して多くのアイテムを持つような時の設定方法.
参考サイト
Rails4で1対多のリレーションをモデルに実装する - Rails Webook
Active Record の関連付け (アソシエーション) - Rails ガイド
railsのbelongs_toとhas_manyとreferencesの使い方について整理する - 巨人の足元でたじlog
scaffoldで下準備
$ rails generate scaffold Author name:string
$ rails generate scaffold Book author:references published_at:datetime
"author:references"に関して、"author_id:integer"でもよいが、referencesとすることで勝手にRailsがidを作ってくれるみたい.
Author側の設定
Author側に:booksをたくさん持っていいよ(has_many)と設定する.
[app/models/user.rb]
class User < ApplicationRecord has_many :books, dependent: :destroy end
Note: 1対多のリレーション時はhas_manyは複数形にする.
"dependent: :destroy"でUserが消されたときに一緒に削除されるよう設定.
他にもオプションがあるので参考サイト参照.
Book側の設定
Book側にauthorについていく(belongs_to)を設定する.
[app/models/post.rb]
class Post < ApplicationRecord belongs_to :author end
デフォルトでは使用するキーはauthor_idが使われる.
キーを変更したい(外部キーを使いたい)場合はforeign_keyオプションで変更できる.
Note: 1対多のリレーション時はbelongs_toは単数形にする.
関連付けのメリット(意味)
"has_many","belongs_to"による関連付けにより以下のメソッドが使えるようになる.
Rails Consoleで試す.
$ rails console
いつも通りに新規作成およびテーブル登録
author1=Author.create(name:'Natsume')
book1を追加してauthor1とリンクさせて作成、テーブルへ追加
book1=author1.books.create(published_at:Time.parse("1905010100000000"))
以下実行結果."author_id"を設定していないのに自動的に設定されていることがわかる.
#<Book id: 3, author_id: 2, published_at: "1905-01-01 00:00:00", created_at: "2019-05-19 12:38:56", updated_at: "2019-05-19 12:38:56">