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 或其他更精简的语法来像命名范围一样优雅地定义自定义关联?
更新
我认为无论如何将这种细节放入关联中并不是一个好主意,因为关联应该始终/主要定义模型之间的基本关系。
最佳答案
解决方案之一是在评论中设置垃圾邮件范围:
model Post
has_many :comments
scope :with_comments, joins(:comments)
end
model Comment
scope :spammy, where(:spammy => true)
end
就模型职责而言,这看起来更清晰一些。在性能方面完全一样:
p.comments.spammy.to_sql
# → SELECT "comments".* FROM "comments"
# WHERE ("comments".post_id = 2) AND ("comments"."spammy" = "t")
额外的好处:您可以从任何其他协会获得垃圾评论。
关于ruby-on-rails - 有什么方法可以使用 AREL 进行自定义关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783853/