0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一対一のアソシエーションの定義方法について

Last updated at Posted at 2020-09-26

・解決したい疑問
 テーブル同士の関係が一対一の時に、どちらのテーブルがhas_oneになるのか知りたい。

・考え方
 二つのテーブルの関係を考えた時に、独立して存在できるテーブルには、has_oneを用いる。
独立して存在できずに、あるテーブルに依存して存在しているテーブルには、belongs_toを用いる。

例えば、twitterのようなアプリがあるとする。ここで、仮にtweetsテーブルとcommentsテーブルがあり、そのアソシエーションが一対一だとする。その時、ツイートはコメントがなくても存在できるが、コメントは、ツイートがなければ、存在することができない。

よって、tweetsテーブルに、has_oneを、commnetsテーブルにbelongs_toを設定すれば良い。
なお、実際には、tweetsに対して、複数のコメントができるのが、絶対的なので、今回の具体例は、あくまで仮の例です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?