有什么方法可以将AREL用于自定义关联吗? [英] Is there any way to use AREL for custom associations?

查看:96
本文介绍了有什么方法可以将AREL用于自定义关联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆