Ruby on rails ActiveRecord查询中的Sql为空
我有类方法来获取帖子,但现在确定如何解决它 所以,有人可以在post上设置标志,但同时post没有任何标志:Ruby on rails ActiveRecord查询中的Sql为空,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有类方法来获取帖子,但现在确定如何解决它 所以,有人可以在post上设置标志,但同时post没有任何标志: Post.find(3).flag #nil 这是获取帖子的自我方法: def self.for_review joins(:flag).where('need_approval = ? and question = ? and DATE(posts.created_at) = ?', "true", "false", Time.now.to_date) .where('
Post.find(3).flag #nil
这是获取帖子的自我方法:
def self.for_review
joins(:flag).where('need_approval = ? and question = ? and DATE(posts.created_at) = ?', "true", "false", Time.now.to_date)
.where('flags.need_check = ? or flags IS NULL', 'false')
end
问题在于第二个where条件
where('flags.need_check = ? or flag IS NULL', 'false')
因为标志为NULL不起作用
有人知道出了什么问题吗?
谢谢问题是连接(:flag)
。它默认为内部联接,因此所有没有标志的帖子都将被拒绝。您需要包含(:flag)。而不是引用(:flag)
另外,
标志为空
没有意义,因为没有称为标志的列。相反,doflags.id为空
连接
默认使用内部连接
;这将只返回至少有一个标志的帖子。您需要一个左连接
。假设一篇文章
有许多标志
:
joins('LEFT JOIN flags ON posts.id = flags.post_id').where(...).where('flags.need_check = ? OR flags.id IS NULL', false)
另外,请删除
true
和false
周围的引号,除非这些字段确实是文本值为“true”和“false”的字符串。谢谢你们两位。这正是我需要的。