Ruby on rails 如何在rails中从两个源建立一对多关系?
我有一个Ruby on rails 如何在rails中从两个源建立一对多关系?,ruby-on-rails,model-associations,Ruby On Rails,Model Associations,我有一个艺术家模型,它有许多评论。还有艺术家有许多演出,而这些演出又有许多评论。评论可以直接针对艺术家,也可以来自艺术家所做的演出。我希望能够做到以下几点: Artist.first.reviews # Should return reviews directly from the artist as well as from artist.gigs def all_reviews Review.where([ '(reviews.reviewer_type = ? AND rev
艺术家
模型,它有许多评论
。还有艺术家
有许多演出
,而这些演出又有许多评论
。评论可以直接针对艺术家
,也可以来自艺术家所做的演出
。我希望能够做到以下几点:
Artist.first.reviews
# Should return reviews directly from the artist as well as from artist.gigs
def all_reviews
Review.where([
'(reviews.reviewer_type = ? AND reviews.reviwer_id IN ?) OR (reviews.reviewer_type = ? AND reviews.review_id = ?)',
'Gig', gigs, 'Artist', id
])
end
我该如何建模?我是否应该在我的模型中定义一种新方法,比如all_reviews
,来获取和合并reviews
,或者通过关联有什么直接的方法?我肯定会选择all_reviews
方法。尽管如此,如何优化它还是很有趣的
您使用的是多态字段还是您的Review
模型属于:gig
和属于:artist
如果案例是第二个,您可以在您的Review
模型中执行以下操作:
def all_reviews
Review.where(['reviews.gig_id IN ? OR reviews.artist_id = ?', gigs, id])
end
这应该没问题,但是如果您使用的是多态字段,我们称之为reviewer
,您可以这样做:
Artist.first.reviews
# Should return reviews directly from the artist as well as from artist.gigs
def all_reviews
Review.where([
'(reviews.reviewer_type = ? AND reviews.reviwer_id IN ?) OR (reviews.reviewer_type = ? AND reviews.review_id = ?)',
'Gig', gigs, 'Artist', id
])
end
两者都可以。请注意,我没有手动测试代码,因此可能会出现错误。多态关联可以帮助您解决此问题。看
在您的情况下,代码如下所示:
Class Artist
has_many :reviews, as: reviewable
has_many :gigs
def all_reviews
reviews + gigs.reviews
end
end
Class Gig
has_many :reviews, as: reviewable
belongs_to :artist
end
Class Reviewable
belongs_to :reviewable, polymorphic: true
end
您也可以将方法all_reviews作为关联,但如果您打算使用关联的方法(添加到集合、查找子对象等),而不仅仅是获取数据,则该方法很有意义。只是想避免使用syntatical sugar的all_reviews方法。我想所有的评论都是应该做的。这难道不只是为了执行+
操作而加载给定艺术家的所有评论吗?我使用或
只是为了避免使用+
操作符,因为这会带来严重的性能问题(内存不足等)是的。我正在使用多态关联。我想所有的评论都是正确的。