【问题标题】:how to only :include based on a conditional statement如何仅 :include 基于条件语句
【发布时间】:2011-07-21 01:50:52
【问题描述】:

我正在尝试根据条件抓取帖子,并且只抓取属于该帖子的 cmets:

即。

# Grab all posts but only include comments that have been approved.
Post.all(:include => :comments, :conditions => ['comments.approved = ?', true])

2011 年 7 月 20 日 10:11 EST 更新

为了澄清,我正在尝试抓取特定用户的所有帖子,并且只抓取该帖子的 cmets。

def grab_posts_and_only_comments_from(user)
   {:include => [:comments], :conditions => ['comments.user_id = ?', user.id]}
end

美国东部时间 2011 年 7 月 20 日 11:34 更新

在选中答案的评论中回答。

【问题讨论】:

  • 这不是一个澄清,实际上是一个新问题:)
  • 对此感到抱歉。你知道我怎么能这样吗?我愿意接受任何建议。

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


【解决方案1】:
Post.includes(:comments).where("comments.approved = ?", true)

EdgeGuides 中有关此功能的文档得到了很大改进。查看第 12.2 节 here

【讨论】:

  • 嗯,只有在该帖子有批准的 cmets 时才会抓取帖子。如果我希望它也包含没有批准的 cmets 的帖子怎么办。
  • 真的吗?你看过生成的 SQL 吗?根据文档,此方法应生成一个 LEFT OUTER JOIN,它将为您提供所有帖子,无论它们是否有 cmets。相反,使用 .join(:cmets) 会产生一个 INNER JOIN,它只包含已批准 cmets 的帖子。
  • 嗯,我不知道怎么了。这是一个 LEFT OUTER JOIN,但由于某种原因,没有匹配条件的 cmets 的帖子不会被返回......
  • 我知道出了什么问题。条件是删除具有空 cmets.approved 字段的行的条目。它应该是:.where("comments.approved = ? OR comments.approved IS NULL",true)
【解决方案2】:

只需添加新关联approved_comments

class Post < AR::Base
  has_many :comments
  has_many :approved_comments, :class_name => "Comment", :conditions => { :approved => true }
end

Post.includes(:approved_comments)
# or for Rails 2.x
Post.all(:include => :approved_comments)

编辑

Post.includes(:approved_comments).where(:approved_comments => {:user_id => user.id})

【讨论】:

  • 对不起,我应该澄清一下我正在尝试创建一个接收变量的范围。我做了上面的编辑。
猜你喜欢
  • 1970-01-01
  • 2016-12-09
  • 2017-10-07
  • 2015-11-28
  • 2013-05-10
  • 2020-12-29
  • 2017-02-03
  • 2020-10-23
  • 2019-12-15
相关资源
最近更新 更多