リレーションの設定

Railsでテーブルのリレーションができるなんてビックリだ。
おまけにちょー簡単。またもやテレビショッピングの外人司会者が出てきて「こんなに簡単なんて信じられるかーい、ジョン」

1:1の場合

どちらか一方のテーブルに『テーブル名の単数形』_idというフィールドを作成する。

authors
id
post_id
post
id
class Author < ActiveRecord:Base
  belongs_to(:post)
end

class Post < ActiveRecord:Base
  has_one(:author)
end

1:nの場合

n側のテーブルに1側の『テーブル名の単数形』_idというフィールドを作成する。

users
id
group_id
group
id
class User < ActiveRecord::Base
  belongs_to(:group)
end

class Group < ActiveRecord:Base
  has_many(:users)
end

n:nの場合

2つテーブル名をアルファベット順に'_'(アンダースコア)で繋げた名前の中間テーブルを作成し、そこにそれぞれの『テーブル名の単数形』_idというフィールドを作成する。

categories
id
categories_projects
category_id
project_id
projects
id
class Category < ActiveRecord::Base
  has_and_belongs_to_many(:projects)
end

class Project < ActiveRecord::Base
 has_and_belongs_to_many(:categories)
end

うーん、『convention over configuration』を強く実感。


はじめよう Ruby on Rails

はじめよう Ruby on Rails