【问题标题】:How to get non associated items on a HABTM association trough active record如何通过活动记录获取 HABTM 关联上的非关联项目
【发布时间】:2012-02-14 16:10:59
【问题描述】:

我有 photoscategories 表和以下模型:


class Category < ActiveRecord::Base
    has_and_belongs_to_many :photos
end

class Photo < ActiveRecord::Base
    has_and_belongs_to_many :categories
end

现在不属于某个类别的照片的语法应该如何?

在 SQL 中我会这样做:

SELECT * FROM photos WHERE id NOT IN (SELECT photo_id FROM categories_photos);

Rails 2.3.10 应用程序中使用 ActiveRecord HABTM 的 Rails 方法是什么

【问题讨论】:

    标签: ruby-on-rails activerecord has-and-belongs-to-many


    【解决方案1】:

    我没有测试过这个。但我想它会在你的照片模型中看起来像这样(作为 named_scoped)。

    named_scope :with_no_category, :conditions => ["photos.id NOT IN (SELECT photo_id FROM categories_photos);"]
    

    那你可以拨打Photo.with_no_category

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 2011-04-29
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      相关资源
      最近更新 更多