命名范围不在,如何?

发布于 2024-09-04 08:16:34 字数 149 浏览 5 评论 0原文

如何在命名范围语法中编写 NOT IN ?例如,User :has_many Photos,我如何定义:

User.has_no_photo

并返回不在 Photo 模型中的所有用户?谢谢!

how can I write a NOT IN in named scope syntax? For example, User :has_many Photos, how can I define:

User.has_no_photo

and returns all users who are not in the Photo model? thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十雾 2024-09-11 08:16:34
named_scope :has_no_photos, :conditions => [ 
  "id NOT IN ?", 
  Photo.all(:select => "distinct user_id").map(&:user_id).map(&:to_i)
]

我假设您有一个标准的“Photo.belongs_to :user”关联和整数键

named_scope :has_no_photos, :conditions => [ 
  "id NOT IN ?", 
  Photo.all(:select => "distinct user_id").map(&:user_id).map(&:to_i)
]

I assume you have a standard "Photo.belongs_to :user" association, and integer keys

多彩岁月 2024-09-11 08:16:34

ActiveRecord 与您在 SQL 中执行的操作没有什么不同:

class User < ActiveRecord::Base
  has_many :photos
  named_scope :has_no_photos,
    :conditions => "(SELECT COUNT(#{Photo.table_name}.*)
                     FROM #{Photo.table_name}
                     WHERE #{Photo.table_name}.user_id = #{User.table_name}.id) = 0"
end

可能有更有效的方法来执行此操作。一种是将 photos_count 存储在用户行上:然后查询变成简单的 photos_count = 0,而不是复杂的联接:

class Photo < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
end

class User < ActiveRecord::Base
  has_many :photos
  named_scope :has_no_photos, :conditions => {:photos_count => 0}
end

ActiveRecord isn't different from what you would do in SQL:

class User < ActiveRecord::Base
  has_many :photos
  named_scope :has_no_photos,
    :conditions => "(SELECT COUNT(#{Photo.table_name}.*)
                     FROM #{Photo.table_name}
                     WHERE #{Photo.table_name}.user_id = #{User.table_name}.id) = 0"
end

There are probably more efficient ways of doing this. One would be to store the photos_count on the user rows: then the query becomes a simple photos_count = 0, instead of a complex join:

class Photo < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
end

class User < ActiveRecord::Base
  has_many :photos
  named_scope :has_no_photos, :conditions => {:photos_count => 0}
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文