Railsで1対1の関係のモデルを定義するにはhas_oneを使います。
記事モデル(Article)が画像モデル(Image)を所有する例で見ていきます。
モデル
モデルは次のようになります。has_oneでImageモデルを所有するのがポイントです。
classArticle< ActiveRecordhas_one:image # Imageを所有end
classImage< ActiveRecordend
マイグレーション
マイグレーションは次のようになります。t.belongs_toでArticleモデルに所属するのがポイントです。
classInit< ActiveRecord::Migrationdefchangecreate_table:articlesdo|t|t.string:title # タイトルendcreate_table:imagesdo|t|t.belongs_to:article # Articleに所属t.string:name # 画像の名前t.binary :file # 画像データendendend
使い方(登録)
# Article作成 article = Article.new( title: "article title" end # has_one関連にあるImageはメンバとしてアクセスできるので、メンバ経由でImageを登録 article.image = Image.new( name: "image name" ) # 最後に保存 article.save!
使い方(参照)
# 1件目のArticleを呼び出す article = Article.first # has_one関係にあるImageはメンバとしてアクセスできるので、メンバ経由でImageを参照 puts artcile.image.name