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.

railsで多対多のモデルを作る

Last updated at Posted at 2018-08-21

いつもやり方を忘れて過去のコードを振り返ったりするので備忘録としてまとめました。

やること

スクリーンショット 2018-08-21 13.55.31.png これのうちの、clips, clip-categories, boardsの多対多の関係を作る (clip modelすでに実装済)

実装

$ rails g model board user:references name:string
# user:referencesはuserに紐づけるために必要なだけなので、本筋とは関係ない
$ rails g model clip_category clip:references board:references
20180821062745_create_clip_categories.rb
class CreateClipCategories < ActiveRecord::Migration[5.2]
  def change
    create_table :clip_categories do |t|
      t.references :clip, foreign_key: true
      t.references :board, foreign_key: true

      t.timestamps
    end
    add_index :clip_categories, [:clip_id, :board_id], unique: true # 追加
  end
end
$ rails db:migrate

board.rbに以下を追加

board.rb
has_many :clip_categories, foreign_key: :board_id, dependent: :destroy
has_many :clips, through: :clip_categories

clip.rbに以下を追加

clip.rb
has_many :clip_categories, foreign_key: :clip_id, dependent: :destroy
has_many :boards, through: :clip_categories

以上で紐づけが完了です。

.rb
clip.boards

などが使えます。

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?