【问题标题】:Is there any way to use AREL for custom associations?有没有办法将 AREL 用于自定义关联?
【发布时间】:2011-08-12 15:14:18
【问题描述】:
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 或其他更精简的语法来定义自定义关联,就像命名范围一样优雅?

更新

我认为无论如何将这种细节放入关联中并不是一个好主意,因为关联应该始终/主要定义模型之间的基本关系。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations arel


    【解决方案1】:

    嗯,可能有更好的方法,但我知道您可以使用 Arel 的 to_sql 功能在关联中使用实际的 Arel 条件(而不是 ActiveRecord::Relations)。

    has_many :spam_comments, :class_name => 'Comment', :conditions => Comment.arel_table[:spammy].eq(true).to_sql
    

    您会注意到实际的 Arel 代码不像 ActiveRecord 关系那样精简。

    我确实在 Rails 主分支中找到了 a comment,它提到将 Arel 谓词作为条件传递,但该代码似乎不在 3.0 分支中。至少我找不到。

    【讨论】:

      【解决方案2】:

      其中一个解决方案是将垃圾邮件范围放在评论上:

      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")
      

      额外的好处:您可以从任何其他协会获得垃圾邮件。

      【讨论】:

      • 是的,我已经看到了……我想无论如何都不能称它为“关联”,因为它没有定义两个模型之间的关系。
      • 性能方面,这是否与通过关联限制查询具有相同的效果? (这里是初学者)
      猜你喜欢
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多