2016-11-29 2 views
0

저는 레일을 처음 사용하고 일부 모델 관계에 문제가 있습니다.관계 모델

나는이 테이블을

+--------------+-----------------+------+ 
| Artists  | Artist Features | Tags | 
+--------------+-----------------+------+ 
| ID   | ID    | ID | 
| Name   | artist_id  | name | 
| Address  | price   |  | 
| Country  | tag_id   |  | 
| Email  |     |  | 
+--------------+-----------------+------+ 

나는 예술가와 예술가 사이의 관계가 artistshas_manyartist_featuresartist_featureshas_many 태그 특징이있다. 내가 쿼리와 위의 구조를 기반으로 모든 아티스트, 기능 및 태그 싶어, artist_idtag_id

은 내가 artists와 해당 artist_features를 얻기 위해 아래 사용했습니다뿐만 아니라 태그도 좀하고 싶습니다 tag_id

@Artists = Artist.all.artist_features 
+1

'has_many' 태그가있는 경우'artist_features' 테이블의 'tag_id' 컬럼이 아닌'tags' 테이블에'artist_feature_id' 컬럼이 있어야합니다. –

답변

1

예술가 기능을하는 경우 has_many 태그를 기준으로, 당신은이 관계의 구조와 일치하는 테이블 컬럼을 변경해야합니다.

has_many/belongs_to 관계는 항상 belongs_to 메서드 호출이있는 모델에 외래 키 열이 있어야합니다.

이 경우 태그 집합을 사용하여 아티스트 기능에서 이러한 태그를 참조 할 수 있습니다. 과 Tag 사이에 ArtistFeatureTag이라는이라는 다른 모델을 추가하면됩니다.

귀하의 모델 구조는 다음과 같을 것이다 :

아티스트 : id, name, address, country, email

class Artist 
    has_many :artist_features 
end 

아티스트 특징 : id, artist_id, price

class ArtistFeature 
    belongs_to :artist 
    has_many :artist_feature_tags 
    has_many :tags, through: :artist_feature_tags 
end 

Ar tistFeatureTag : id, artist_feature_id, tag_id

class ArtistFeatureTag 
    belongs_to :artist_feature 
    belongs_to :tag 
end 

태그 : id, artist_feature_id, 여분의 표는 직관적 보일 수도 있지만, 아티스트 기능과 태그, 즉 다수의 관계를 저장하는 것이 필요 name

class Tag 
    has_many :artist_feature_tags 
    has_many :artist_features, through: :artist_feature_tags 
end 

아티스트 기능은 동일한 태그를 참조 할 수 있으며이 참조는 ArtistFeatureTag의 형식을 취합니다.

이것은 기본적으로 has and belongs to many-type relationship이지만, 분명히 이해할 수 있기 때문에 관계 모델을 명시 적으로 작성하기로 결정했습니다.

+0

Chris, My tags 테이블 감사합니다. 동일한 태그 이름을 가진 행을 복제하고 싶지 않습니다. 따라서 내 태그에 artist_feature_id가 있으면 해당 시나리오에서 작동하지 않습니까? 아마도 내 구조가 분명하지 않을 수 있습니다! – Adam

+0

나는 내 대답을 업데이트 할 것이다. –

+0

크리스, 감사합니다! 이것은 내가 필요한 것입니다. – Adam