【问题标题】:Creating a named_scope for "no children" in a has_many association在 has_many 关联中为“无子项”创建 named_scope
【发布时间】:2010-09-09 12:40:29
【问题描述】:

我想为零帖子的博客设置一个 named_scope。

以下不起作用。

class Post < ActiveRecord::Base
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts

  named_scope :has_no_posts, :conditions => "blogs.id NOT IN (SELECT blog_id FROM posts)"
end

【问题讨论】:

    标签: ruby-on-rails activerecord named-scope has-many


    【解决方案1】:

    你确定它不起作用吗?它对我有用。

    【讨论】:

      【解决方案2】:

      不确定为什么您的代码不起作用。它会出错还是没有返回您期望的结果?能把它生成的sql贴一下吗?

      不过你可以试试:

      named_scope :has_no_posts, :include => [:posts], :conditions => "posts.id IS NULL"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 2011-10-19
        • 1970-01-01
        • 2014-06-03
        • 1970-01-01
        相关资源
        最近更新 更多