【问题标题】:Rails 3 Query Interface: using associated modelsRails 3 查询接口:使用关联模型
【发布时间】:2010-10-20 10:17:28
【问题描述】:

我将使用通用博客示例。

class Post < ActiveRecord::Base
  has_many :comments
end
class Comment < ActiveRecord::Base
  belongs_to :post
end

查询 Post 时,如何访问其关联(即 :cmets)?

这应该是世界上最简单的事情了,但我还没有找到任何关于它的文档。甚至http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interfacehttp://m.onkey.org/2010/1/22/active-record-query-interface 也无济于事,基本上是在说“现在有像连接和包含这样的方法来做与SQL 语句相同的事情。”是的,谢谢。

所以这是我想做的非常简单的事情,它们不起作用,但我想要完成的事情应该很明显:

Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)

我们如何在不使用带有 SQL 味道的 ruby​​ 代码的情况下完成这些工作(从而违背了 Active Record 的目的)? 谢谢:)

【问题讨论】:

  • Post.includes("cmets").where(:cmets => {:author_id => current_user.id}) 似乎适用于第二个,尽管必须少一些 SQLish / 更多Railsish 的方法(即类似于我在问题中写它的方式)。由于类中的“has_many”方法调用,ARel 不应该要求我们在查询中使用 SQLish“include”方法。它至少应该这么聪明。
  • 很高兴看到我两年半前的问题。现在这很容易。

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


【解决方案1】:

如果您在 Post 上为 cmets 设置counter_cache,您可以直接查看它有多少 cmets,而无需查询,这样更容易、更快捷。

这将处理您提出的第一个和最后一个问题。

然后你可以像这样查询它们,

  Post.where(:comments_count >= 10)
  Post.order(:comments_count)

但你最好为此设置范围。

我不确定你想对第二个问题做什么,你想显示当前用户评论过的所有帖子吗?

【讨论】:

    【解决方案2】:

    Post.where(:cmets.count >= 10)

    Post.find(:all).select{|p| p.comments.count >= 10)
    

    Post.where(:cmets.author_id == current_user.id)

    Post.find(:all).select{|p| p.comments.select{|c| c.author_id == current_user.id } }
    

    Post.order(:cmets.count)

    Yikes, this one beats me.
    

    另外,我的两篇文章都对 SQL 有点重。我知道人们用

    做起来会更优雅
    Post.find(:all, :conditions => blah blah blah..
    

    但我不知道该怎么说。对不起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2011-05-20
      相关资源
      最近更新 更多