ruby-on-rails - 有什么方法可以使用 AREL 进行自定义关联吗?

标签 ruby-on-rails ruby activerecord associations 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 或其他更精简的语法来像命名范围一样优雅地定义自定义关联?

更新

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

最佳答案

解决方案之一是在评论中设置垃圾邮件范围:

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/

相关文章:

ruby-on-rails - Rails form_for with file_field and remote => true and format => :js

ruby-on-rails - 使用连接表的行存在作为别名

mysql - 根据数组顺序对 Rails 查询进行排序

ruby-on-rails - 列中数组的唯一值

ruby-on-rails - Ruby Gem 开发入门

ruby 1.9.x,奇怪的解析,这是怎么回事?

ruby-on-rails - Rails : what does schema. rb 做什么?

ruby-on-rails - Rails Cross Origin Headers Set,XMLHttpRequest 无法加载 http ://www. d1.com/sign_in,Access-Control-Allow-Origin 不允许 Origin

javascript - 嵌套表单中输入的 onclick 设置值

javascript - respond_to do |格式|在 Rails 5 应用程序中给出 "UnknownFormat in UsersController#show"