2016-11-29 111 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'标签,那么您应该在'tags'表上有'artist_feature_id'列,而不是'artist_features'表上的'tag_id'列。 –

回答

1

如果一个艺术家的特征has_many标签,那么你就需要改变你的表列,以配合这种关系结构。

A has_many/belongs_to关系始终要求belongs_to方法调用的模型具有外键列。

在这种情况下,您想拥有一组标签并允许艺术家功能引用这些标签。我们可以通过在ArtistFeatureTag之间添加另一个模型(称为ArtistFeatureTag)与表artist_feature_tags来完成此操作。然后

你的模型结构应该是这样的:

艺术家:idnameaddresscountryemail

class Artist 
    has_many :artist_features 
end 

艺术家特点:idartist_idprice

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

氩tistFeatureTag:idartist_feature_idtag_id

class ArtistFeatureTag 
    belongs_to :artist_feature 
    belongs_to :tag 
end 

标签:idartist_feature_idname

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,我的标签表我不想复制具有相同标签名称的行。因此,在我的标签上添加artist_feature_id将无法在该场景中使用?也许我的结构不是很清楚! – Adam

+0

我明白了,我会更新我的答案。 –

+0

谢谢Chris,非常感谢!这正是我需要的。 – Adam