任何方式使用AREL定制联想? [英] Any way to use AREL for custom associations?
问题描述
model Post
# ActiveRecord associations have tons of options that let
# you do just about anything like:
has_many :comments
has_many :spam_comments, :conditions => ['spammy = ?', true]
# In Rails 3, named scopes are ultra-elegant, and let you do things like:
scope :with_comments, joins(:comments)
end
有没有办法使用AREL,或以其他方式精简语法,为优雅的定义自定义协会评为命名范围?
Is there any way to use AREL, or an otherwise leaner syntax, to define custom associations as elegantly as named scopes?
更新
我已经决定这是不是一个好主意,把那种细节到一个协会,无论如何,因为协会应始终/大部分定义模型之间的基本关系。
I've decided it's not a good idea to put that sort of detail into an association anyway, because associations should always/mostly define the basic relationships between models.
推荐答案
解决的办法之一就是把对垃圾邮件的评论范围:
One of the solutions is to put spammy scope on Comments:
model Post
has_many :comments
scope :with_comments, joins(:comments)
end
model Comment
scope :spammy, where(:spammy => true)
end
这看起来对于责任的模拟了一下清洁。性能方面它是完全一样的:
This looks a bit cleaner with respect to model responsibilities. Performance-wise it's exactly the same:
p.comments.spammy.to_sql
# → SELECT "comments".* FROM "comments"
# WHERE ("comments".post_id = 2) AND ("comments"."spammy" = "t")
附加的好处:你可以得到垃圾邮件的评论从任何其他协会
The added benefit: you can get spammy comments from any other associations.
这篇关于任何方式使用AREL定制联想?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!