Ruby/RubyOnRails-日本語
Rails 一日一つメソッド (Day41) Associations_has_and_belongs_to_many
아랑팡팡
2024. 2. 26. 19:21
728x90
Rails 一日一つメソッド (Day41) Associations_has_and_belongs_to_many
1. has_and_belongs_to_manyとは
- 二つのモデルの多対多 (many-to-many)関係を設定する時に使う RailsのActiveRecordメソッド。
- 二つのモデルの間を join tableで関係を定義し、複数のインスタンスとの関連を持つ事ができる。
2. 多対多の関連
- 多対多関係を設定するには join tableが必要になる。
例)Bookモデルと Authorモデル
- 一つの本は、複数の Authorを持つ事ができる。
- Authorは、複数の本を持つ事ができる。
この時に、books_authors join tableが使われる。
1) Model定義
- 二つのモデルに has_and_belongs_to_manyメソッドで関係を定義する。
class Book < ApplicationRecord
has_and_belongs_to_many :authors
end
class Author < ApplicationRecord
has_and_belongs_to_many :books
end
2) joinMigration
- books_authors join tableを生成する(book_id, author_id )の外来キーを含む。
class CreateBooksAuthorsJoinTable < ActiveRecord::Migration[7.1]
def change
create_table :books_authors, id: false do |t|
t.references :book
t.references :author
end
end
end
rails c
book = Book.find(1)
author = Author.find(1)
book.authors << author
book.autors.delete(author)
多対多の関連を宣言で、bookモデルと Authorモデルのインスタンスを探したり、複雑なクエリを実行するときに有用に使用できる。
728x90
반응형
LIST