Railsで1対多のモデルを作るには、belongs_toとhas_manyを使います。
作者:1と記事:多の関係を作ってみます。
Step1. モデルの作成
作者モデルを作ります。has_many :複数形として、記事モデルに繋ぎます。
class Author < ApplicationRecord has_many :articles end
記事モデルを作ります。belongs_to :単数形として、作者モデルに繋ぎます。
class Article < ApplicationRecord belongs_to :author end
注意:Rails5では、belongs_toがデフォルトでnilを許可していないため、許可する場合は次のようにします。
class Article < ApplicationRecord belongs_to :author, optional: true end
Step2. マイグレーション
記事テーブルのarticlesと作者テーブルのauthorsを作成します。
記事テーブルのarticlesでは、t.belongs_to :単数系で作者テーブルのIDであるauthor_idカラムを作成しています。
class Init < ActiveRecord::Migration[5.0] def change # 作者テーブル create_table :articles do |t| t.string :title t.belongs_to :author end # 作者テーブル create_table :authors do |t| t.string :name end end end
マイグレーションします。
$ rake db:migrate
使い方
article = Article.first author = Author.first
articleに登録されているauthorを確認する。
p article.author
逆にauthorに登録されているarticleを確認する。
p author.articles
articleにauthorを登録する。belongs_toへ値を格納した時は自動で保存されないので、saveを呼ぶ。
if article.author != author article.author = author article.save! end
逆にauthorにarticleを追加する。has_many側へ格納する場合は自動保存される。
unless author.articles.include?(article) author.articles << article end