【Rails】일대일대다의 어소시에이션
2898 단어 RailsActiveRecord
어소시에이션이 잘 되지 않고 시간을 녹여 버렸기 때문에, 그런 과거의 자신과 있을지도 모르는 미래의 누군가를 위해서 남겨 둡니다.
테이블 구조
User 모델과 Tag 모델의 중간 테이블에서 파생된 TagSetting 모델을 만들었습니다.

다만, 이번 이야기에는 User 모델은 그다지 관계가 없습니다.
또, 이 후 「tag_users와 tag_settings를 따로따로 하지 않아도 되지 않을까?」라고 하는 지적을 받아 테이블 구조를 바꾸었습니다. 그래서, 예로서는 조금 부적절할지도 모릅니다만 용서를.
모델 연관
user.rb
class User < ApplicationRecord
has_many :tag_users
has_many :tags, through: :tag_users
has_many :tag_settings
end
tag_user.rb
class TagUser < ApplicationRecord
belongs_to :user
belongs_to :tag
belongs_to :tag_setting
end
tag_setting.rb
class TagSetting < ApplicationRecord
has_one :tag_user
has_one :tag, through: :tag_user
belongs_to :user
end
tag.rb
class Tag < ApplicationRecord
has_many :tag_users
has_many :tag_settings, through: :tag_users
end
주의점
중간 테이블에 연관 추가
has_many :tag_users
없이 has_many :tag_settings, through: :tag_users
를 정의할 수 없습니다.또한 중간 테이블에 대한 연관을 위에서 설명해야합니다.
단수형·복수형에 주의한다
has_many :tag_settings, through: :tag_users
has_many
의 때는 :through
도 복수형has_one :tag, through: :tag_user
has_one
때는 :through
도 단수형링크
Reference
이 문제에 관하여(【Rails】일대일대다의 어소시에이션), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/aiandrox/items/c2cf479dc96a8168347d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)