LoginSignup
7
4

More than 5 years have passed since last update.

Ruby on Rails のマイグレーションで references によって has_one, belongs_to 関連を作るときに unique 制約をつける

Last updated at Posted at 2016-11-10

例えば、人間と種(たね)のモデルを作り、それらを関連付け、
「ひとりひとり違う種を持つ」という制約を加えたい場合、 has_one 関連を用います。

$ bin/rails g model Seed person:references

とすると

    create_table :seeds do |t|
      t.references :person, index: true, foreign_key: true
      # 略
    end

という内容のマイグレーションができます。
データベース上でも制約を付けたい場合、person_id もユニークにしたいので、

t.references :person, index: { unique: true }, foreign_key: true

とすることで、データベースにも制約をつけることができます。

補足

厳密には、index: にハッシュを渡すことで、 add_index メソッドに渡せるオプションを渡すことができます。

t.references は t.belongs_to とすることもできます。

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