Ruby on Rails에서 다대다 테이블 디자인을 움직이면서 이해해보기
기사 내용
잘못된 부분 등이 있으면 지적하십시오.
다 대다 연관이란?
다 대 다 연관은 두 테이블 간의 관계가 "복수 대 다중"이라는 것을 의미합니다.
예를 들어, Qiita에도 구현되는 블로그 기사에 태그를 지정하는 기능을 구현하고 싶다고 가정하면 하나의 블로그 기사에 여러 태그를 연결할 수 있습니다. 그리고 하나의 태그를 여러 블로그 기사와 연결할 수 있다는 기능을 구현합니다.
중간 테이블을 만들고 두 테이블을 연결
다대다 연관을 구현하기 위해 이번에는 중간 테이블을 사용하는 방법을 설명합니다.
「개인적으로 중간 테이블이라고 해도 핀과 오지 않는다…」라고 하는 느낌이었으므로 이미지를 섞어 보겠습니다.

articles 테이블과 tags 테이블을 연결하는 중간 테이블에서 각각의 id를 관리하는 것으로 다대다의 어소시에이션을 구현합니다.
만약 articles 테이블의 레코드가 삭제되었을 때, 관련 첨부의 중간 테이블의 레코드도 삭제되고 싶으면
Rails에서 다 대다 연관 구현
각 모델을 생성합니다.
$ rails g model Article title:string body:string
$ rails g model Tag name:string
$ rails g model ArticleTagRelation article:references tag:references
:references
를 지정하면 각 모델과 연관된 상태로 생성됩니다.app/models/article.rb
class Article < ApplicationRecord
has_many :article_tag_relations, dependent: :destroy
has_many :tags, through: :article_tag_relations
end
app/models/tag.rb
class Tag < ApplicationRecord
has_many :article_tag_relations, dependent: :destroy
has_many :articles, through: :article_tag_relations
end
app/models/article_tag_relation.rb
class ArticleTagRelation < ApplicationRecord
belongs_to :article
belongs_to :tag
end
has_many
로 연결하는 경우 모델 이름을 복수형으로 지정하고 belongs_to로 연결할 경우 모델 이름을 단수로 지정합니다.:dependent
는 article 및 tag 레코드가 삭제된 경우의 동작을 지정합니다.:destroy
를 지정하면 연관된 중간 테이블의 레코드가 삭제됩니다.※
:destroy
로 삭제했을 경우, 삭제하는 레코드 수분 SQL이 실행된다Rails console에서 실제로 확인해보기
절차
rails new
구현을 확인 rails console
에서 데이터 만들기 DB Browser for SQLite 사용 방법
테스트용 애플리케이션 작성
$ rails new test_app
모델링
$ rails g model Article title:string body:string
$ rails g model Tag name:string
$ rails g model ArticleTagRelation article:references tag:references
※rails db:migrate 실행
모델 파일과 연결
article.rb
class Article < ApplicationRecord
has_many :article_tag_relations, dependent: :destroy
has_many :tags, through: :article_tag_relations
end
tag.rb
class Tag < ApplicationRecord
has_many :article_tag_relations, dependent: :destroy
has_many :articles, through: :article_tag_relations
end
article_tag_relation.rb
class ArticleTagRelation < Application
belongs_to :article
belongs_to :tag
end
Rails 콘솔에서 데이터 생성
$ rails c
> Tag.create(name: 'Rails')
> Article.create(title: 'タイトル', body: 'テスト', tag_ids: [1])
DB Browser for SQLite에서 article_tag_relation 테이블 확인
Article 모델의 레코드를 삭제하고 article_tag_relation.rb의 레코드도 함께 삭제되었는지 확인
> Article.first.destroy
삭제되면 다 대다 연결이 완료되었습니다.
참고
Reference
이 문제에 관하여(Ruby on Rails에서 다대다 테이블 디자인을 움직이면서 이해해보기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ryutaro9595/items/e021eb789914cead4677텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)